What is a constructor?
It is a method of a class that we call once to create an object/instance of a given class. Here we place the logic that should be done during the construction. For example, we can get and set parameters from outside the class to create an object with these specific parameters.
Now you can go back to the Cake class and generate a constructor (alt + Enter) -> generate constructor. You will see this little window:
Here you can choose what parameters you need for the constructor. We will pick all of them so just press ok.
And you will get something like that:
public Cake(string flavor, int layers, bool isHomemade) { Flavor = flavor; Layers = layers; IsHomemade = isHomemade; }
Default constructor
The default one will be used if there is no constructor in the class declaration. It will have no logic and does nothing but memory allocation for your object.
You can try to remove our constructor and use the default one. To do that, you will have to change one extra line.
Replace this line:
public string Flavor { get; set; }
With this:
public string ? Flavor { get; set; }
This question mark will allow us to make this field null by default.
You would ask what the default value of other data types is.
For numerical types (like int), it will be 0. For a boolean, it will be false. And for other reference types, it will be null.
And now, you can execute our program again, and it works as before.
However, If you use those attributes in your program, you may want to avoid nulls and zeroes, as they can cause some errors.
In this case, I would suggest you give default values to your fields as follow:
public string Flavor { get; set; } = "Default cake"; public int Layers { get; set; } = 2; public bool IsHomemade { get; set; } = false;
Or you can rewrite the default constructor:
public Cake() { Flavor = "Default flavor"; Layers = 2; IsHomemade = false; }
Multiple constructors
Now when you know that attributes of a class may be assigned with default or provided values, you can mix it. That means you can create constructors for different cases.
For example you know that Cakes in your program usually will not be homemade. Or if you have specified a default value in the attribute declaration, how it was shown before. You can simplify your constructor to this:
public Cake(string flavour, int layers) { Flavor = flavor; Layers = layers; }
Moreover, you can have both at the same time. And the framework will know which one to pick depending on your input.
So both will work:
Cake myCake = new Cake("Choco", 2, true); Cake anotherCake = new Cake("Vanilla", 5);
Copy constructor
You also can create a constructor that will copy an existing instance of your class:
public Cake(Cake toCopy) { Flavour = toCopy.Flavour; Layers = toCopy.Layers; IsHomemade = toCopy.IsHomemade; }
In other words, you can create an instance from whatever you need. Just pass the necessary information to the correct constructor.