Search code examples
c#.netreference-type

Setting a type reference type to null doesn't affect copied type?


Why does this produce "0" ?

object a = 0;
object b = a;
a = null;
Console.WriteLine(b.ToString()); // Produces "0"
Console.Read();

Doesn't b point to the same location and setting a = null effectively makes b null?


Solution

  • A picture is worth a thousand words:

    enter image description here

    Setting a = null removes a's reference (the arrow) to the object (the boxed integer 0). It does not affect the object itself. b still references the unchanged object afterwards.