Q:

A question about Parameter passing in c#

The below example is got from Jon Skeet's article, "Parameter passing in C#".
My question is: Why variable y is NOT null in the first example while we see that it has been changed in the second example:
1-
void Foo (StringBuilder x)
{
    x = null;
}

...

StringBuilder y = new StringBuilder();
y.Append ("hello");
Foo (y);
Console.WriteLine (y==null);

2-
void Foo (StringBuilder x)
{
    x.Append (" world");
}

...

StringBuilder y = new StringBuilder();
y.Append ("hello");
Foo (y);
Console.WriteLine (y);

Thank you

A:

y is not null in the first example, precisely because the argument is passed by value. The argument expression (simply y) is evaluated, and its value (a reference to a StringBuilder is copied into the parameter variable (x) as the initial value.
Changing the value of x does not change the value of y.
The second example doesn't change the value of the parameter (x) - it changes the data within the object that x refers to. The value of y still hasn't changed: it still refers to the same StringBuilder object, it's just that that object now contains different data.
If I give you a piece of paper with my home address on, and you go to that address and paint the house red, you're not changing anything about the piece of paper, are you? And if you did cross out my address on the piece of paper (as in the first example) that wouldn't change my idea of my address - just as changing the value of x doesn't change the value of y.

A:

In both examples the reference to the StringBuilder is being passed by value.
Think of y as the holder of the address of the actual StringBuilder.
The address itself is being copied to Foo's as stack parameter so the assignment x = null in the first example changes the copied address and not the actual address stored in y.
On the second example x.Append refers to the same instance that y points to and changes it, hence the change is visible.

