Question

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?

Was it helpful?

Solution

A picture is worth a thousand words:

enter image description here

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

OTHER TIPS

You want to know where the cookies are. You have a piece of paper, labelled "A". On the paper is written in pencil "123 Sesame Street".

The paper is not a cookie. The address is not a cookie. The paper contains a reference to an address which contains the cookie.

You obtain a second piece of paper, labelled "B". On that piece of paper, you make a copy of the contents of "A". Now you have two pieces of paper, both say "123 Sesame Street". Both tell you where the cookies are.

You take piece of paper "A" and erase it. "A" no longer refers to the location of the cookies. B still does.

You are assuming that saying "b = a" means to write on B "for the location of the cookies, please consult paper A". But that is not what "b = a" means in C#; it means make a copy of the reference, not make an alias of the reference.

In C# to make an alias of the reference you use the "ref" keyword, confusingly enough:

void M(ref object b)
{
    b = null;
}
...
object a = 0;
M(ref a);
// "b" now becomes an alias for "a"; when "b" is nulled out, so is "a" because they are the same variable with two different names.

In C# you can only do this when calling a method that takes a ref parameter like this. The feature you want is not supported in C#, though we have considered supporting it:

object a = 0;
ref object b = ref a;
a = null; // b and a are aliases for the same variable now.

Do you have a compelling need for this feature? If you do, please let me know what it is. That will help us prioritize whether or not the feature is worth doing in a hypothetical future version of C#.

UPDATE: It got done! This feature was added to C# 7.

You are setting the reference to null, you are not changing the object the reference points to. a and b are two separate references, hence setting a to null will of course leave b unchanged (Think "pointer"), it just means that a now points to null ("nowhere").

Boxing (which is the process that happens here) is pretty nicely explained in the following article with examples at what happens in memory.

Here's a description of what's going on:

object a = 0; // pointer a = 0xSomeA
object b = a; // pointer b = 0xSomeB
a = null; // nulling a, now 0x00; b still the same
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top