Reputation: 331
I thought that a List holds references of objects, so I thought I could create an object of my own custom class called "Node", add it to a list and then later delete the object by assigning it with null. (I know I could use remove from the list, but that's not what I want to do.) So when I print the list again, it still prints with the name of the object "testNode" even though I assigned it with null. What can I do to add a reference to a list?
Node testNode = new Node("Name", id);
List<Node> listNodes = new List<Node>();
listNodes.Add(testNode);
for (int i = 0; i < listNodes.Count; i++)
listNodes[i].ToString();
testNode = null;
for (int i = 0; i < listNodes.Count; i++)
listNodes[i].ToString();
Upvotes: 2
Views: 86
Reputation: 43876
What you add to the list is a reference to that instance of Node
. Not a referernce to your variable.
With
testNode = null;
you only assign null
to your variable. This does nothing to the real instance testNode
was referencing. And it does not change the list or remove the reference from the list.
So the only way to remove the reference from the list is - well - Remove
:
listNodes.Remove(testNode);
Upvotes: 4