Custom constructors
We saw how to create new instance of an object using the following syntax:
new ObjectType();
This way, you are calling the public implicit constructor. In simple words, the default constructor creates an instance without taking any parameters. All C# objects that are not using custom constructors will be using an implicit constructor.
Another great ability is to write your own constructors. Why? It will have you typing a lot of code, it's fun to use, and it makes code much easier to read.
Custom constructor should be written within the code block of the class. Have a look at the example first and then we'll go through the actual syntax. A custom public constructor for the Person
could look like this:
As you can see, it's nothing scary. A custom constructor is a public method taking some parameters. The generic syntax for the public constructor will always start with the keyword public
followed by a class name. Inside the brackets, we can write any parameters we wish.
I try...