2.4.9 How to Utilize Constructors

Since the beginning of your time in these classes you have been using constructors but haven't known it. Any time you have instantiated an object you are "calling" a constructor.

If there is not a constructor explicitly defined within the class being instantiated, C# knows that an instance should still be created. So what does a constructor look like anyway? It looks like this:

Now if we F11 on that constructor call, the debugger will step into the constructor.

If we didn't explicitly define that Employee constructor and pressed F11 on the constructor call it would have passed right over the call and still instantiated the object.


We will be going more in-depth in the following week about constructors with parameters, but for now just know that constructors are called every time a new object is instantiated and they are used to assign values/call methods/instantiate other objects right when the object is instantiated.


Take the Employee, for example. If every time we instantiated an Employee we wanted them to have the same favorite food we can do that in the constructor by assigning the field in the constructor body like this:

Now when the constructor is called and the debugger goes through the constructor body we can see that the favoriteFood field has been assigned to but nothing else.


Over time you will discover nuances about constructors, but for now know that they are called whenever an object is instantiated and everything we put in a constructor body will occur for every instance created.