Constructors in C#

10 maart 2021 om 10:00 by ParTech Media - Post a comment

To develop any application, defining the variables forms a very critical part of the process. In the .Net framework, the definition of simple data types to their default values is done by C#. However, while creating specific classes or struct, one would have to decide default values which can be achieved by using constructors.

Constructors are typically utilized for initializing the attributes of a class. It also allocates memory for the class while initializing the data members of a class.

In this post, we are going to understand what are constructors in C# and how you can define the different types of constructors in it.

Table of contents

● What is a constructor?

● Syntax of a constructor

● Salient Features of constructors

● What are the types of constructors?

● Conclusion

What is a constructor in C#?

Constructors are the methods that are invoked when an instance of a class or struct is created. Constructors are generally used to initialize the private fields in the class or struct when an instance of the class is created. A default constructor is created for a class when no constructor is explicitly defined by the programmer. So, each class will always have at least one constructor even if none is created by the programmer. This default constructor would initialize all the numeric data values to zero and objects and string to null.

Syntax of a constructor

Following is the general syntax of a constructor:-

Above is the general syntax of constructor the access specifier various according to the need of the program.

Example:-

In the above image, you can see that Fruits is the class in which a constructor with the same name as the name of the class is created. The constructor is public, so there is no limitation to its access. Hence when objects of the class are created, the data members of this constructor will also be accessible in the child classes.

Salient features of constructors

Key features of constructors are:

  • Any number of constructors can be there for a class.
  • It doesn’t have a return type. This includes even void.
  • The constructor of a static class can never be parameterized.
  • Only one static constructor can be created within a class.
  • Constructors can be overridden.

What are the types of Constructors?

Default Constructor

When no parameter is passed to the constructor, the constructor is said to be a default constructor. The major drawback of a default constructor is that we cannot initialize the different instances of classes with different values as all the instances will be created using the same values that are defined in the default constructor. This default constructor would initialize all the numeric data values to zero and objects and string to null.

Following is the example of default constructor -

**

Output:

Parameterized Constructor

When a constructor takes at least one parameter, then it is called a parameterized constructor. The advantage of parameterized constructor over a default constructor is that we can initialize different instances of a class with different values making it more dynamic and robust.

Following is the example of parameterized constructor:-

Output:-

Copy Constructor

A copy constructor is a constructor that copies the variable from another object while creating a new object. The copy constructor is mainly used to initialize a new instance with values of a previous instance.

Syntax of copy constructor is as follows:-

In the above image, a copy constructor is created using an existing instance. The copy constructor copies all data members of this existing instance.

Static constructors

When a constructor is defined using the static keyword, then it gets invoked only once for all the instances i.e., when the first instance of the class is created. The use of static constructor in C# is to initialize the static fields of the application which need to be executed only once for all instances.

Key features of static constructors:-

  • No access specifiers are given to the static constructors nor does it have any parameters.
  • A static constructor is called only when the first instance of the class is created.
  • A static constructor cannot be directly called.
  • The execution of a static constructor in a program cannot be controlled by the user.

Syntax of a static constructor is as follows:-

**

In the above image, we can see that a static keyword is used to create a static constructor. Inside a static constructor, there can only be data members that are to be initialized only once during the execution of the program.

Private Constructor

When a constructor is created with a private access specifier it is called a private constructor This type of constructor can only be used when all the members of a class are static.

Syntax of a private constructor is as follows:-

**

In the above image, we can see that a private keyword is used to create the private constructor. Any instance cannot call the private constructor. The private constructor only contains static data members.

Inheritance in constructor

The constructor also plays an role in inheritance. When a class is inherited, the derived class inherits all the public property and methods. However, the derived class cannot inherit the constructor of the base class. To initialize the derived and base class, respective constructors have to be used.

Here are two scenarios that can help us to understand this better.

Scenario 1: How to initialize objects, if the base class has no constructor and the derived class has a constructor

  class Program

  {

​    static void Main(string[] args)

​    {

​      Console.WriteLine("Hello World!");

​      PassengerVehicle obj = new PassengerVehicle("XYZ", 2021, 4);

​      var result = obj.GetVehicleDetails();

​    }

  }

  class Vehicle

  {

​    public string ManufacturerName { get; set; }

​    public int YearOfManufacturing { get; set; }

  } 

  class PassengerVehicle : Vehicle

  {

​    int AllowedPassengers { get; set; }

​    public PassengerVehicle(string name, int year, int count)

​    {

​      ManufacturerName = name;

​      YearOfManufacturing = year;

​      AllowedPassengers = count;

​    }

​    public string GetVehicleDetails()

​    {

​      return $"It is a {ManufacturerName} car manufactured in the year {YearOfManufacturing}   and {AllowedPassengers} persons can travel in this car";

​    }

  }  


Output - It is a XYZ car manufactured in the year 2021 and 4 persons can travel in this car.

In the above example, Vehicle is the base class and Passenger vehicle is the derived class. The vehicle class does not have a constructor for itself. However, a Passenger vehicle has a constructor for itself and the properties are initialized using the constructor of the class.

Scenario 2: How to initialize objects, if the base class and derived class both have a constructor

  class Program

  {

​    static void Main(string[] args)

​    {

​      Console.WriteLine("Hello World!");

​      PassengerVehicle obj = new PassengerVehicle("XYZ", 2021, 4);

​      var result = obj.GetVehicleDetails();

​    }

  }

  class Vehicle

  {

​    readonly string ManufacturerName;

​    readonly int YearOfManufacturing;

​    public Vehicle(string name, int year)

​    {

​      ManufacturerName = name;

​      YearOfManufacturing = year;

​    }

​    public string GetManufacturer()

​    {

​      return ManufacturerName;

​    }

​    public int GetYear()

​    {

​      return YearOfManufacturing;

​    }

  }


  class PassengerVehicle : Vehicle

  {

​    int AllowedPassengers { get; set; } 

​    public PassengerVehicle(string name, int year, int count) : **base(name, year)**

​    {

​      AllowedPassengers = count;

​    }

​    public string GetVehicleDetails()

​    {

​      return $"It is a {GetManufacturer()} car manufactured in the year {GetYear()} and {AllowedPassengers} persons can travel in this car";

​    }

  }

Output - It is a XYZ car manufactured in the year 2021 and 4 persons can travel in this car.

In the above example, the base class Vehicle as well as the derived class PassengerVehicle both have their constructors. To initialize the properties of the base class, the keyword base is used in the constructor of the derived class. The values that are obtained as input are being passed to the base class constructor.

A class can may no constructor or have as many constructors as it needs. In the below example, we will see how to reutilize an already existing constructor that is present in the class.

  class Program

  {

​    static void Main(string[] args)

​    {

​      Console.WriteLine("Hello World!");

​      PassengerVehicle obj = new PassengerVehicle("XYZ", 2021, 4);

​    }

  }

  class PassengerVehicle

  {

​    string Name;

​    int Year;

​    int Passenger;  

​    public PassengerVehicle(string name, int year)

​    {

​      Name = name;

​      Year = year;

​    }

​    public PassengerVehicle(string name, int year, int passengers) : **this(name, year)**

​    {

​      Passenger = passengers;

​    }

  }

In the above example, there are two constructors present in the PassengerVehicle class. The object initialization in the main class is being done using the constructor with three parameters. Now, there is another constructor in the class that accepts two parameters. Though the object initialization is being called with three parameters, internally, the class reutilizes the two-parameter constructor and initializes the properties.

Conclusion

This post has covered some of the key concepts of constructors along with its uses. In your next C# application, use constructors whenever you are defining private fields in the class or struct when an instance of the class is created.