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:

Custom constructors

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 to keep my code consistent and a have a simple naming rule for constructor parameters. I always use a lowercase p followed by the parameter name. This way, I avoid confusion inside the constructor body. So, the firstName parameter is called pFirstName and the lastName parameter is called pLastName. Feel free to set your own rule for this. However, this one is quite common. I have seen it being used by another developer and adopted it.

Let's try to implement it now. Add the two constructors to the Person method:

Custom constructors

You are probably wondering why we are adding an empty constructor at all. It's simply to keep a bit of flexibility if we want to instantiate the object without any data. This way, we will also stop any errors coming up inside the LearningObjects class, as we are using implicit constructor there.

Let's focus on constructor within lines 16 to 19. As you can see, there's nothing scary. It is exactly what you would expect to see, right? We are taking two string parameters, naming them according to the p rule, and assigning them to the variables within this object.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset