Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Difference between instance and a reference variable in C#

I have a noob question.

Consider this code:

Sample a = new Sample();

a is an instance of type Sample – right?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So if we write

Sample a

is this also creating an instance of Sample? What is the difference between both the statements – or are both the same?

>Solution :

Note: all of this assumes that Sample is a class.

Consider this code

Sample a =new Sample();

a is instance of Sample of Type Sample. Right?

No, a is a variable. The value of a is a reference. That reference refers to an instance of Sample.

You can have two variables with references to the same object:

Sample a = new Sample();
Sample b = a;

These are two independent variables – if you say a = null for example, that doesn’t change the value of b. But with just the code above, the values of both variables are references to the same object, so any change you make to the object using one variable would be visible via the other variable. For example, if Sample has a simple property called text, then this code:

Sample a = new Sample();
Sample b = a;
a.Text = "text";
Console.WriteLine(b.Text);

… will print "text".

It’s a bit like two different people having addressbooks, and both of them have an entry in their addressbook for "Fred", which initially has the same address in both addressbooks:

  • If one person changes their addressbook, crossing out the original address for "Fred" and writing a new address, that doesn’t change the other addressbook
  • On the other hand (assuming the same starting situation), if one person goes to the address in their addressbook and paints the front door red, then if the other person goes to the address in their addressbook, then they’ll see a red front door.

So If we write

Sample a

Is this also creating an instance of Sample.

No, that’s just declaring a variable. If it’s a field, it will have a default value of null. If it’s a local variable, you won’t be able to read the value until you’ve assigned a value to it in the code.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading