7

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

ehh
  • 3,412
  • 7
  • 43
  • 91
  • msdn docs explains this very case: https://msdn.microsoft.com/en-us/library/14akc2c7(v=vs.120).aspx; just RTFM – ASh Nov 02 '15 at 06:32
  • http://stackoverflow.com/questions/4482264/list-collection-object-as-method-parameter – Fayyaz Naqvi Nov 02 '15 at 06:33

2 Answers2

7

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)

Andrii Tsok
  • 1,386
  • 1
  • 13
  • 26
5

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>();
}
Backs
  • 24,430
  • 5
  • 58
  • 85
  • 3
    Collections are passed as a reference by default, thus stating that list would not be replaced without ref keyword is wrong. – Aistis Taraskevicius Apr 25 '18 at 10:48
  • Interesting concept. Even though lists are references, by not declaring the ref in the parameter determines whether a new instance will overwrite the original reference or create a separate instance in memory away from the original referenced list. By finding an actual difference in the behaviour, I believe that this is indeed the correct answer, even though initially it seems incorrect! – Radderz Feb 02 '23 at 10:52