A variable is not an object, it is only a reference to an object. So, for instance, in the following example, there are two variables that both reference the same object:
Label label1 = new Label();
Label label2 = label1;
label1.Text = "1";
label2.Text = "2";
After executing that code, you will see that label1.Text
equals "2" rather than "1". That is because they both reference the same Label
object, so when you set label2.Text
, it will change for both variables. If, however, you instantiated two separate label objects, the result would be different, for instance:
Label label1 = new Label();
Label label2 = new Label();
label1.Text = "1";
label2.Text = "2";
In this second example, each variable points to a different Label
object (i.e. a different instance of the Label class). Therefore, after running this code, label1.Text
will equal "1" and label2.Text
will equal "2", as you would expect.
There are good reasons why both of these options are important and available to you. For instance, lets say you want to make a method that sets the Text
property of a Label
, for instance:
void SetLabelText(Label labelToSet)
{
labelToSet.Text = "text";
}
And you may call the method like this:
Label label1 = new Label();
SetLabelText(label1);
In this case, the labelToSet
variable in the SetLabelText
method will reference the same object as the label1
variable, so when 'SetLabelText
sets labelToSet.Text
to "text", it's not creating a new Label
, it's just setting the text on an existing Label
object that was passed as a parameter to the method, which is exactly what you would want to happen.
Since any variable may be set to either a new object or an existing object, it is considered "null" until it has been assigned to an object. As I said at first, the variable is not the object, it's just the reference to the object. If a variable references no object at all (it's initial state), it is null
and will throw an exception if you try to use it. For instance:
Label label1;
label1.Text = "1"; // Throws a null reference exception
You can declare as many variables as you want, but they will all be null
until you actually instantiate at least one object and set them to it. To instantiate an object (i.e. create a new instance of a class), you must use the new
keyword (e.g. new Label()
).
However, everything I've said so far is only true of "Reference Types" (class). That is not the case with "Value Types" (struct). When you declare a variable as a value type, for all practical purposes, it is actually the object. Many simple data types such as int
are value types. So for instance:
int x;
int y;
x = 1;
y = x;
y = 2;
After running the above code, x
will equal 1
and y
will equal 2
. Setting y = x
does not cause y
to reference the same object as x
. Rather, it copies the value from x
to y
, thereby creating a new value type object.