Search code examples
c#referenceref

Saving reference in a Field


I'm trying out the following code:

public partial class Test: Window
{
    public Test(ref List</* Type */> LList)
    {
        [...]
        this.ListField = LList;

    }

    private  List</* Type */> ListField;
}

C# doesn't save a reference in "ListField". Example:

Test test = new Test(ref /* List</* Type */>-variable*/)

---------

public partial class Test: Window
{
    public Test(ref List</* Type */> LList)
    {
        [...]
        this.ListField = LList;

    }

    private  List</* Type */> ListField;

    private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
        ListField = null;
    }
}

After having closed the form the Object given to public Test(ref List</* Type */> LList) has not changed (it's not "null").

SO how ca I save A reference in "ListField"?


Solution

  • (I'm sure this is a duplicate, but I suspect it would be hard to find examples due to terminology overloading.)

    It definitely saves a reference in ListField. That's all it can do - the value of ListField can only ever be a reference, because List<T> is a class.

    What it sounds like you really want is to keep the aliasing behaviour of ref, but that only applies to parameters - never fields. It's important to distinguish between "pass by reference" as a parameter passing style, and references themselves (important in terms of the difference beteween classes and structs).

    Basically, you can't do what you want directly. You could create a Wrapper<T> class, make ListField a Wrapper<List<T>> and pass a reference (by value) into the constructor, but you can't just use ref to do what you want.