To understand what happens, it is crucial to know that a class is a reference type. I.e., variables of this type contain either null
or a reference to an object. They do not contain the object itself or the values stored in this object.
This is different from a value type like int
. A variable of this type effectively contains the number it represents.
In void MakeNull(Node node)
, the parameter node
holds a copy of the reference passed to it (because it is passed by value, i.e., without the ref
or in
or out
keyword). You are only settings this copy to null
. If you want to set the variable of the caller to null
, you must pass it by reference:
void MakeNull(ref Node node)
{
...
node = null;
...
}
Call it with
MakeNull(ref main);
or
MakeNull(ref Child);
Now, node
is not a copy of the caller's variable but an alias of it. E.g., when you call
MakeNull(ref main);
... node
is just another name for main
. Setting node = null;
now effectively sets main = null;
.
Why does it work for node.Id = 5;
then? Because node
holds a reference to a Node
object, and thus, the Id
of this object is changed. Note that in your implementation you have a copy of a reference to a Node
object in node
, not a copy of the object itself.
See also my answer to this SO question: Setting a type reference type to null doesn't affect copied type?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…