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?
Note: all of this assumes that Sample
is a class.
Consider this code
Sample a =new Sample();
a
is instance ofSample
of TypeSample
. 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:
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.