Constructors

Constructors are called whenever an object is created for a class or struct type. They can help us to set some default values against the member variables present in these types. 

In Chapter 2Understanding Classes, Structures, and Interfaces, while understanding the difference between a class and struct type, we mentioned that, unlike classes, structs do now have a default constructor. That constructor, in programming terms, is known as a parameter less constructor. If a programmer does not specify any constructor for the class, then whenever an object is created for the class the default constructor triggers and sets default values against the member variables present in the class. The default values are set in accordance with the default values of the type of those member variables. 

In terms of syntax, a constructor is just a method the name of which is the same as that of its respective type. In the method signature, it has got a parameter list that can be mapped to the member variables present in the type. It does not have any return type. 

Please note that a class or struct can have multiple constructors each differing with each other based on the parameter list present in the method. 

Let's look at a code example in which we will implement constructors:

public class Animal
{
public string Name;
public string Type;

public Animal(string Name, string Type)
{
this.Name = Name;
this.Type = Type;
}
}

In the preceding code example, we have declared an Animal class with two member variables, Name and Type. We have also declared a two-parameter constructor in which we are passing Name and Type as string parameters. Using the this operator, we are then assigning the values passed to the member variables present in the class. 

We can use the following code implementation to call this constructor:

Animal animal = new Animal("Bingo", "Dog"); 

In the next section, we will look at how named parameters are implemented in C#.

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

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