Classes are reference types. That means that when we create a new instance of a class and store it in a variable, the variable is a reference to the object.
Let’s see what’s happening behind the scenes. When this code is run:
Dissertation diss1 = new Dissertation();
Dissertation instance is constructed and stored in the computer’s memory. You can imagine a slot in your computer holding the instance’s type, property values, etc.
diss1 is a reference to that location in memory.
diss1 is not the actual object, it is a reference to the object. Thus an object can have multiple references:
Dissertation diss1 = new Dissertation(); Dissertation diss2 = diss1;
Now there are two references to the same location in memory: we can say that
diss2 refer to the same object. If changes are made to that object, then they will be reflected in both references to it:
Dissertation diss1 = new Dissertation(); Dissertation diss2 = diss1; diss1.CurrentPage = 0; diss2.CurrentPage = 16; Console.WriteLine(diss1.CurrentPage); Console.WriteLine(diss2.CurrentPage);
CurrentPageproperty of the same object (first setting it to
You can imagine references like directions to a house: they tell you where to find the house, but they are not the house itself!
Create a new
Diary object with a current page of
5 using the constructor
new Diary(5). Store a reference to that object and name it
dy1. Its type should also be
Create another reference to that object and name it
dy2 by calling its
Flip() method. This increases the
CurrentPage property by 1.
Print out the
CurrentPage property for both
dy2. They should be the same!