c# 3.0 - Difference between instance and a reference variable in C# - Stack Overflow

admin2025-04-27  6

I have a noob question.

Consider this code:

Sample a = new Sample();

a is an instance of type Sample - right?

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?

I have a noob question.

Consider this code:

Sample a = new Sample();

a is an instance of type Sample - right?

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?

Share Improve this question edited Jan 11 at 13:29 marc_s 757k184 gold badges1.4k silver badges1.5k bronze badges asked Jan 11 at 13:05 sampath ssampath s 551 silver badge8 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 12

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.

转载请注明原文地址:http://anycun.com/QandA/1745710426a91148.html