-2

What is the difference between the code below? Both methods achieve the same output of removing 4 from the list.

static void Main(string[] args)
{
    var list = new List<int> {1, 2, 3, 4, 5, 6, 7, 8, 9};
    ModifyList(ref list);
    Console.WriteLine(string.Join(", ", list));

    list.Add(4);
    ModifyList(list);
    Console.WriteLine(string.Join(", ", list));

    Console.ReadLine();
}

public static void ModifyList(ref List<int> list)
{
     list.Remove(4);
}

public static void ModifyList(List<int> list)
{
     list.Remove(4);
}
Justin Adkins
  • 1,214
  • 2
  • 23
  • 41

2 Answers2

4

In this case, both do exactly the same thing. The difference between passing the argument in by ref is that if you assign to the variable itself (eg. list = new List<int>();, it will update the reference of the caller to point to the new list as well.

See Passing Reference-Type Parameters (C# Programming Guide) for more info.

willaien
  • 2,647
  • 15
  • 24
1

In this case the only difference is under the hood and not easily noticeable, the difference is that in the ModifyList(ref List<int> list) the list object is passed by reference and so the original reference (managed pointer) is the same as the original object passed, while in the second case the reference is copied to another reference so the list argument is basically a reference to another reference that point to the real object .

The result you get is the same, because in C# with safe reference is totally transparent to you but if you would have used C or C++ with raw pointers you would have noticed that in the second case you would had to dereference the pointer two times to access the object ...

aleroot
  • 71,077
  • 30
  • 176
  • 213