Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing List<int> by ref [duplicate]

Tags:

c#

ref

Possible Duplicate:
passing in object by ref

With the code below, the output would be:

Without:
With:1

Code:

    static void Main(string[] args)
    {
        var listWithoutRef = new List<int>();
        WithoutRef(listWithoutRef);
        Console.WriteLine("Without:" + string.Join(" ", listWithoutRef));

        var listWithRef = new List<int>();
        WithRef(ref listWithRef);
        Console.WriteLine("With:" + string.Join(" ", listWithRef));
    }

    static void WithoutRef(List<int> inList)
    {
        inList = new List<int>(new int[] { 1 });
    }

    static void WithRef(ref List<int> inList)
    {
        inList = new List<int>(new int[] { 1 });
    }

By just looking at this, I would have said that a List is on the Heap, and so is passed by ref anyway, so they should be the same? Am I misunderstanding the ref keyword? Or am I missing something else?

like image 742
Richard Avatar asked Mar 27 '26 03:03

Richard


1 Answers

Am I misunderstanding the ref keyword? Or am I missing something else?

Yes. You're not passing the list itself to the method, but rather passing the reference to the list by reference. This lets you change the reference (the List<int> that listWithRef actual refers to) within the method, and have it reflect.

Without using the ref keyword, your method can't change the reference to the list - the actual list storage mechanism is unchanged in either case.

Note that this isn't required if you just want to use the list. You can call List<int>.Add within either method, for example, and the list will get new items added to it. Ref is only required with reference types to change the reference itself.

like image 158
Reed Copsey Avatar answered Mar 29 '26 16:03

Reed Copsey