Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a list parameter as ref [duplicate]

Tags:

c#

list

ref

What is the advantage of passing a list as parameter as ref in C#? List is not a value type so every changes done on it will reflect after returning the function.

class Program
{
    static void Main(string[] args)
    {
        var myClass = new MyClass();
        var list = new List<string>();
        myClass.Foo(ref list);

        foreach (var item in list)
        {
            Console.WriteLine(item);
        }
    }
}

class MyClass
{
    public void Foo(ref List<string> myList)
    {
        myList.Add("a");
        myList.Add("b");
        myList.Add("c");
    }
}

I can remove "ref" and it will work fine. So my question is for what usage do we need to add ref keyword for lists, arrays... Thanks

like image 764
ehh Avatar asked Nov 02 '15 06:11

ehh


2 Answers

The ref keyword causes an argument to be passed by reference, not by value. List is a reference type. And in your example you're trying to pass object by reference to method argument also using ref keyword.

It means that you're doing the same thing. And in this case you could remove ref keyword.

ref is needed when you want to pass some Value type by reference. For example:

class MyClass
{
    public void Foo(ref int a)
    {
        a += a;
    }
}

class Program
{
    static void Main(string[] args)
    {
        int intvalue = 3;
        var myClass = new MyClass();
        myClass.Foo(ref intvalue);
        Console.WriteLine(intvalue);    // Output: 6
    }
}

Some additional specification information you can find there: ref (C# Reference)

like image 137
Andrii Tsok Avatar answered Sep 20 '22 06:09

Andrii Tsok


This will create new list and it will replace list variable from outside:

public void Foo(ref List<string> myList)
{
    myList = new List<string>();
}

This will not replace list variable from outside:

public void Foo(List<string> myList)
{
    myList = new List<string>();
}
like image 23
Backs Avatar answered Sep 22 '22 06:09

Backs