Compartir a través de


.Net List: set null on copy of list item isn’t reflected on original list

Technorati Tags: .Net List

Hi There, I am Syam Pinnaka, Dev in IAM services team at Microsoft.

I was trying to fix a bug in my code about a week back and was stumbled upon this. Think it will be useful to others. The story goes like this.

I have a collection (List) of my custom objects and took a copy of one of the list items. example below.

     class myObject
     {
         public myObject(int id, string name)
         {
             this.id = id;
             this.name = name;
         }
  
         public int id
         {
             get;
             set;
         }
  
         public string name
         {
             get;
             set;
         }
     }
             static List<myObject> items = new List<myObject>();
  
             myObject first = new myObject(1, "first");
             myObject second = new myObject(2, "second");
  
             items.Add(first);
             items.Add(second);
  
             myObject firstCopy = items[0];

After taking the copy, I try to make some changes to the copy and use it and finally set it to null.

             firstCopy.id = firstCopy.id + 1000;
             //Use firstCopy, code stripped for brevity..
             firstCopy = null;

now what do you think will be there items[0]? If you think its null that’s incorrect. it will still have the modified value and is not set to null. We can see this by checking the object.

             foreach (myObject item in items)
             {
                 if (item != null )
                     Console.WriteLine("In main: id = " + item.id + ", name = " + item.name);
                 else
                     Console.WriteLine("In main: item is null");
             }

The output is as below.

image

This is because the copy here is just a pointer to original list item and setting null on copy is like removing the reference and not release the original item. The only way to make the original item as null is to reference original item and set explicit null on that like below.

       item[0] = null;

This is a good learning for me and hope will be useful to others as well.

Thanks for reading and happy coding!