Constructors in C#

C# is an Object-Oriented programming language and, as such, most of the concepts in C# relate to objects. But what is the thing that is responsible for creating objects in C#? Here is a hint: constructors. In this blog post, we will be discussing things like what constructors are and what the various types of constructors are that developers can define in C#.

What is a Constructor in C#?

Constructors are the method that is invoked whenever an object of a class or struct is instantiated. Constructors are mainly used for initializing private data members at the time when an object of a class is created. Each class in C# always has at least one constructor, even if the programmer does not define any constructor explicitly, a default constructor is created for that class. The default constructor initializes the data members to default; for example, properties having type numbers to zero and string and object types to null.

Syntax of a Constructor in C#

The C# constructor has the following syntax:

  class Example{
     
    //Constructor 
     Example(){
 
          // any C# legal statement
 
     }
  }

Here is some example code showing how to use a C# constructor:

public class Cars{
 
   // constructor
   public Cars(){
       // code
   }
}
 

In this example, as you can see, we have created a class named Cars, in which we have created a constructor with the same name as that of our class. Remember that the constructors are defined publicly, so they can be accessed from anywhere in the class.

Features of Constructors in C#

The following are some common features of constructors in C#:

  • Constructors have the same name as that of the class
  • You can create as many constructors as you want
  • You can create only one static constructor within a class
  • Constructors in a static class cannot be parameterized
  • Constructors do not return any value. They also do not have any return type – not even void

Read: An Object Oriented Programming (OOP) Primer in C#

Types of Constructors

So, you should now have an idea of what constructors are and what their significance is in Object-oriented programming. In the next section, we will be discussing the different types of constructors you can define in C# according to your application needs.

Default Constructor

Default constructors do not take any arguments. If you do not create any constructor in a class, C# will create a default constructor to instantiate the class objects and initialize the default values to the data members (non-static variables), as depicted in the following C# code-snippet:

     class Car
     {
         public string brand, model;
 
         // Default Constructor
 
         public Car()
         {
            brand = "Ford";
            model = "Mustang";
         }
     }
 
    class Program
    {
        static void Main(string[] args)
        {
            Car carObj = new Car();
            Console.WriteLine(carObj.brand);
            Console.WriteLine(carObj.model);
            Console.WriteLine("\nPress Enter Key to Exit");
            Console.ReadLine();
        }
    }
 
 

In this example, we have created a class named Car and defined the constructor method Car() without any parameter. This constructor is called Default constructor because when we instantiate an object of this class, this constructor will be automatically called by the runtime and initializes those parameter values.

So, if you execute this program, you will get the following output:

C# Constructors

Parameterized Constructors in C#

In C#, if you create any constructor with at least one parameter then it will be called a parameterized constructor. Each instance of the class is initialized with the defined parameter values.

The following is an example demonstration of how you can create a parameterized constructor in C#:

      class Car
     {
         public string brand, model;
         
         // Default Constructor
         public Car(string a, string b)
         {
            brand = a;
            model = b;
         }
     }
 
    class Program
    {
        static void Main(string[] args)
        {
            Car carObj = new Car("BMW","X5");
            Console.WriteLine(carObj.brand);
            Console.WriteLine(carObj.model);
            Console.WriteLine("\nPress Enter Key to Exit");
            Console.ReadLine();
        }
    }
 

As you can see in the above code example, we have created a class named Car and a constructor Car(string , string ) with parameters. This parameterized constructor will be called automatically when we create an object of this class with the required parameter. So when you execute the above code, you will get the following output:

C# Constructor Tutorial

Private Constructors in C#

In C#, when a constructor is created with a private access specifier, it is called a Private constructor. This type of constructor is required when developers want to implement a factory or singleton pattern. Thus, using private constructors is beneficial to use in the scenarios where we want to prevent other classes from creating an object of a particular class.

Here is an example of how to use private constructors in C#:

     class Car
     {
         private Car()
         {
             Console.WriteLine("Private Constructor called!");
         }
         
         public string brand, model;
        
         public Car(string a, string b)
         {
            brand = a;
            model = b;
         }
     }
 
    class Program
    {
        static void Main(string[] args)
        {
            // Car carObj = new Car();   Error: This statement will cause                    an error because the constructor is inaccessible here
 
            Car carObj2 = new Car("Fiat","500X Lounge");
            Console.WriteLine(carObj2.brand + ',' + carObj2.model);
            Console.WriteLine("\nPress Enter Key to Exit");
            Console.ReadLine();
        }
    }
 

In the above code snippet, we have created a class named Car with a private constructor Car() and also defined another default parameterized constructor. If you try to create an object of this class using the statement Car carObj =new Car(); then C# will toss an error because you have called a private constructor. Calling a private constructor means the constructor is not accessible and that is why you won’t be able to create an instance of this class.

Read: Visual Studio Code Extensions for Higher Productivity

Static Constructors in C#

In C#, you can create a static constructor using the static keyword. Static constructors are used to initialize the static data members of the class, which needs to be executed only once for all instances.

Key Features of Static Constructor:

  • Static constructors can’t be called directly
  • Static constructor doesn’t take any parameters nor do they have any access specifiers.
  • Static constructor gets executed only when the first instance of the class is created
  • A programmer has no control over the execution of static constructor

For example, consider the following .NET code snippet:

   class Car
     {
         static Car()
         {
             Console.WriteLine("Static Constructor called!");
         }
         
     
         public Car()
         {
            Console.WriteLine("Default Constructor called!");
         }
     }
    
    class Program
    {
        static void Main(string[] args)
        {
            Car carObj = new Car();
            Console.WriteLine();
            Car carObj2 = new Car();
            Console.WriteLine("\nPress Enter Key to Exit");
            Console.ReadLine();
        }
    }

In this example, we have created a static constructor and a default constructor in the same class. The static constructor will be called only once, when we create the first instance of this class. So, if you try to run this code snippet, you will get the following output:

Constructors in C#

As you can see in the above screenshot, first we created an object of this class, then both the static constructor and default constructor were executed. For the second time, when we created an object of this class, then only the default constructor was executed. So, in that way, you can use static constructor in C# where you want to execute a specific action, such as initializing the data members only once throughout program execution.

Read: C# Back to Basics: Static Constructors

Copy Constructors in C#

A copy constructor is a constructor that is used to initialize a new instance of a class with the values of another instance. In simpler words, a copy constructor is a constructor that copies the data of an object into another object.

For demonstration purposes, we can define a copy constructor in C# in the following way:

      class Employee
     {
        public string name, designation;
        
        // Parameterized Constructor
        public Employee(string a, string b)
        {
            name = a;
            designation = b;
        }
        
        // Copy Constructor
        public Employee(Employee emp)
        {
            name = emp.name;
            designation = emp.designation;
        }
     }

     class Program
     {
        static void Main(string[] args)
        {
          // Employee object with Parameterized constructor
            Employee empObj = new Employee("Katie Brock", "Accountant");
        
          // Another Employee object (empObj2) by copying employee details
            Employee empObj2 = new Employee(empObj);
            empObj2.name = "Amber Webb";
            empObj2.designation = "Software Engineer";
            Console.WriteLine("Default constructor instance:" +
                                empObj.name + ", " + empObj.designation);

            Console.WriteLine("Copy constructor instance:" +
                              empObj2.name + ", " + empObj2. designation);

            Console.WriteLine("\nPress Enter Key to Exit..");
            Console.ReadLine();
        }
     }

If you observe the above code example, we have created an instance of copy Constructor empObj2. With the help of the copy constructor, we have copied the properties of empObj object to empObj2 object. In the next couple of lines, we have changed the property values of empObj2 by re-assigning values to name and designation property. Note that, as we have changed the property values of empObj2, it will not affect the property value of the existing instance of empObj.

If you execute the above code, you will get the following result:

Working with C# Constructors

As you can see, we have successfully initialized a new instance with the value of an existing instance, but the property value of the existing instance is not affected.

Overloading a Constructor in C#

In C#, constructors can be overloaded. You can define more than one constructor with the same name but with different parameters. This is called constructor overloading.

For example, consider the following code-snippet:

     class Car
     {
         public string brand, model;
 
        // Default Constructor
         public Car()
         {
             brand = "Audi";
             model = "A3";
         }
 
         public Car(string a, string b)
         {
            brand = a;
            model = b;
         }
     }
 
    class Program
    {
        static void Main(string[] args)
        {
            Car carObj = new Car();
            Car carObj2 = new Car("Fiat","500X Lounge");
            Console.WriteLine(carObj.brand + ',' + carObj.model);
            Console.WriteLine(carObj2.brand + ',' + carObj2.model);
            Console.WriteLine("\nPress Enter Key to Exit");
            Console.ReadLine();
        }
    }
 

In the above example, we have created a class Car with the constructor Car(). We overloaded this constructor by creating another constructor Car(string, string) with the same name but with different parameters. If you execute the above program, you would find that when we create an instance of our class with or without a parameter based on our requirement, the respective constructor will be called.

Here is the output of running this C# code example:

C# Constructors

Conclusion of Constructors in C# Tutorial

In this C# programming tutorial, we have covered some of the key concepts of C# constructors and their significance in Object-oriented programming. In your next C# application, it is recommended to use constructors whenever you define any private data members in a class or struct.

Read more C# programming tutorials.

Tariq Siddiqui
Tariq Siddiqui
A graduate in MS Computer Applications and a Web Developer from India with diverse skills across multiple Web development technologies. Enjoys writing about any tech topic, including programming, algorithms and cloud computing. Traveling and playing video games are the hobbies that interest me most.

More by Author

Must Read