Derrick Jeevan Derrick Jeevan -3 years ago 92
C# Question

Original Values changes are not reflecting in reference types variable

object a = "1411";
object b = a;

Console.WriteLine("Before Value of a " + a);
Console.WriteLine("Before Value of b " + b);

a = "5555";

Console.WriteLine("After Value of a " + a);
Console.WriteLine("After Value of b " + b);



Before Value of a 1411

Before Value of b 1411

After Value of a 5555

After Value of b 1411

After Value of b also should changed to 5555 right? since b is reference types variable.

Answer Source

Let's take this code piece by piece to see what it does:

a = "1411";

This will store a reference to an object into the variable a. The object is a string, and allocated on the heap (since it's a reference type).

So there are two pieces involved here:

  • The variable a
  • The object (string) that it refers to

Then we have this:

b = a;

This will make the variable b reference the same object that a refers to.

References internally are implemented as memory addresses, and thus if (example) the string object lives at address 1234567890, then the values of the two variables would both be that address.

Now, then you do this:

a = "5555";

This will change the contents of the a variable, but the b variable will be left unchanged.

This means that b still refers to the old object, at address 1234567890, whereas a will refer to a different string object.

You did not change the object itself, that both a and b were referring to, you changed a.

As Marc said in a comment, you can liken this to giving you the address of a house on a piece of paper. If you give a piece of paper to your friend, writing up the same address on that second piece of paper, you are referring to the same house on both.

However, if you give your friend a paper with a different address on it, even if the two houses looks the same, they're not the same house.

So there's a big difference between reference type and variable containing a reference.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download