John V
John V

Reputation: 5047

C# reference variables use clarification

Being not a programmer, I would like to understand the following code:

A a=new A();
B a=new B();

a=b;      
c=null;

b=c; 

If the variables are holding only reference, will 'a' be null in the end?

Upvotes: 1

Views: 229

Answers (2)

Habib
Habib

Reputation: 223257

Assuming that all the objects a,b,c, are from the same class, a will not be null. It will hold the value of the reference b before its assignment to c.

Lets assume you have the following class

class Test
{
    public int Value { get; set; }
}

Then try:

Test a = new Test();
a.Value = 10;
Test b = new Test();
b.Value = 20;
Console.WriteLine("Value of a before assignment: " + a.Value);
a = b;
Console.WriteLine("Value of a after assignment: " + a.Value);
Test c = null;
b = c;
Console.WriteLine("Value of a after doing (b = c) :" + a.Value);

Output would be:

Value of a before assignment: 10
Value of a after assignment: 20
Value of a after doing (b = c) :20

Upvotes: 6

Marc Gravell
Marc Gravell

Reputation: 1062780

You need to divorce two concepts in your mind; the reference and the object. The reference is essentially the address of the object on the managed heap. So:

A a = new A(); // new object A created, reference a assigned that address
B b = new B(); // new object B created, reference b assigned that address
a = b; // we'll assume that is legal; the value of "b", i.e. the address of B
       // from the previous step, is assigned to a
c = null; // c is now a null reference
b = c; // b is now a null reference

This doesn't impact "a" or "A". "a" still holds the address of the B that we created.

So no, "a" is not null in the end.

Upvotes: 5

Related Questions