0.6.1 How to Instantiate Objects in C#

Object instantiation takes place when the 'new' keyword is attached to a class and assigned to a field or variable. The image below can be read as: The ComoZoo field is assigned to a new instance of the Zoo class.

Each week in this course you will see an object diagram for most of your assignments. It will indicate the objects that have to be instantiated and configured by having the field values set in order to complete the assignment.

So say you were given the task to instantiate a Food item for the Attendant with the diagram below.

Let's break down what the diagram is telling us.

  1. This is the field. In this case it's the Attendant's Food field.
  2. This line is an object reference. This line is made whenever an object is assigned to a field. In this case, the Attendant's Food field is a Food object.
  3. This is the class/type of object. In the instructions anything blue is something "new". In this case, since the Food field already existed, the Food object is the only new thing being made.
  4. This is the object node. This represents the whole object. This box is added to an object diagram when the new command is used.

Now combining how to instantiate objects and the object diagram we were given, we can write the line of code that instantiates the Attendant's Food.

So when we run the application after setting a breakpoint we can see that the Attendant's Food field is null.

Once we execute that line, then, we can see that that Food field is now referencing an instance of the Food class.