Search code examples
c#arraylistref

Set object to null, from list


I have a variable, then add that variable to list. If i set list[0] to null, its just removed from list and the variable still stays not null.

And if i set the variable to null, the one in the list stays not null.

    var s = new String("Test".ToCharArray()); //Example of class

    var list = new List<String>();

    list.Add(s);

A:

    s = null;

    Debug.Log( list[0] ); //Test
    Debug.Log( s ); //Null

B:

    list[0] = null;

    Debug.Log( list[0] ); //Null
    Debug.Log( s ); //Test

My actual code is much more intricate with multiple variables and objects, some variables holding an instance to the same object (neither are structs), one has a list with all of the objects.

Doing 'list[0] = null' only empties the 0th spot in that list instead of making that object be null, and i want the object to be set to null too.

I expected that both A and B would make both of them null. Can someone explain why its not behaving like that, and how to make it behave like that?

And since the list holds a reference to 's' , why does 's = null' not change the list item to null?


Solution

  • As mentioned in the comments, this is just not how C# works. In particular, C# does not allow to store references to an object directly, only as part of another object. Hence, the following would work:

    class Variable<T>
    {
       public Variable(T value) { Value = value; }
       public T Value { get; set; }
    }
    
    var s = new Variable<string>("Test");
    var list = new List<Variable<string>>();
    
    list.Add(s);
    

    Then you have A

    s.Value = null;
    
    Debug.Log( list[0].Value ); //Null
    Debug.Log( s.Value ); //Null
    

    and B

    list[0].Value = null;
    
    Debug.Log( list[0].Value ); //Null
    Debug.Log( s.Value ); //Null