I have a class Simple, which contains an integer, number.
Using this code:
Simple b = new Simple();
List<Simple> list = new List<Simple>();
list.Add(b);
b.number = 6;
b = null;
Debug.WriteLine("The value of b is " + b);
Debug.WriteLine("And the value of the clown in the list is " + list[0].number);
The Debugs return The value of b is and And the value of the clown in the list is 6.
I can assume that by adding b to the list, then a reference to b is stored. Then, by nulling b, list still contains a reference to the object that was b and thus can print out the value of number.
However, if I can change a member of b and have that reflected by the reference stored in the list, then why doesn’t the b = null reflect on the value of list[0]? I can only assume this has something to do with value and reference.
Help anyone?
bandlist[0]are both variables that reference the same location in memory. When you setb = null, you’re settingb‘s reference tonull.list[0]is still pointing to the original location in memory and is unchanged.When you change a property of
b, (for instanceb.A) you’re effectively sayingWhen you access
Avialist[0], you’re sayingEDIT: As another example, if
b = someObjectandlist[0] = someObject, settingb = someOtherObjectwill not changelist[0]…list[0]is still pointing tosomeObject.So, to answer your question, you’d have to set
b = nullandlist[0] = nullto “null” the object they’re both referencing. Even that, though, doesn’t do what it seems like you want. All that will do is orphan the object in memory and allow theGarbage Collectorto clean it up whenever it gets around to it.