C# Constructor

The C# constructor is a type of method defined inside a class for initializing that class’s variables. In general, the name of the constructor should be the same as the class name. The C# constructor doesn’t return any value, and hence it is said to be a non-value returning method.

In general, every class holds some fields or variables. The values required for executing the C# class are sent to it using constructors. The syntax of the C# constructor is as shown below

[<Access specifier>] <ConstructorName>([<parameter list>])
{
   Statements;
}

As we already said that an object is created to access the fields and the member functions of the C# class. In contrast, the C# constructor is useful to create the instance or object of the class.

A programmer must define constructor explicitly inside a class. Otherwise, while execution, the C# compiler creates a constructor by default. We call it an implicit constructor or default constructor. 

The C# Constructors are either static or non-static. Except for the constructor, that defined with the access specifier static, all are non-static constructors only.

Let us see how a C# default constructor called to initialize the variables when constructor not defined inside the class.

using System;

namespace CSharp_Tutorial
{
    class Program
    {
        int a;
        bool b;
        static void Main(string[] args)
        {
            Program p = new Program();
            Console.WriteLine("value of integer a is: " + p.a);
            Console.WriteLine("value of boolean b is: " + p.b);
            Console.ReadLine();
        }
    }
}

OUTPUT

C# Constructor 1

In the above example program, a is an integer and b is a boolean variable defined respectively. Here, we have not defined constructor to initialize those variables but asked to print the values of them.

While execution, the compiler creates an implicit constructor to initialize variables a, b, and prints the default values. i.e., the value of integer variable a = 0 and Boolean variable b as false.

NOTE: Even though a constructor not defined inside the class. When we try to call the constructor, then the compiler will call the parameterless constructor by default. Hence the constructor called by the compiler, which was not defined explicitly, called the implicit constructor.

Types of Constructors in C#

The following are the different types of constructors in C# programming language.

  • Default constructor (parameterless constructor).
  • Parameterized constructor.
  • Copy constructor.
  • Static constructor.

C# Default Constructor (or) parameterless constructor

A constructor that doesn’t take any values (or) a constructor that doesn’t have any parameters called as a parameterless constructor or default constructor.

The Syntax of the C# default constructor or the parameterless constructor is as shown below.

using System;

public Class_name ()
{
       --statements--
}

Let us see the same example program that executed previously with a small change of defining constructor explicitly.

using System;

namespace CSharp_Tutorial
{
    class Program
    {
        int a;
        bool b;
        public Program()
        {
            Console.WriteLine("Parameterless constructor is called");
        }
        static void Main(string[] args)
        {
            Program p = new Program();
            Console.WriteLine("value of integer a is: " + p.a);
            Console.WriteLine("value of boolean b is: " + p.b);
            Console.ReadLine();
        }
    }
}

OUTPUT

C# Default Constructor 2

While execution, the compiler will call the C# parameterless constructor, that we defined explicitly.

Program() is a parameterless constructor created explicitly. By using this, we created an object p and tried to print the values of integer variable a and Boolean variable b. Since we have not initialized the variables, the compiler would print the default values and assign them to the integer and Boolean variables.

C# Parameterized Constructor

A constructor defined with the parameters (or) a constructor that takes values said to be a parameterized constructor. The C# programmer should explicitly define the parameterized constructor.

The syntax of the C# Parameterized Constructor is

public Class_name (<parameter_list>)
{
       --statements--
}

Let us see an example of this Parameterized Constructor

using System;


namespace CSharp_Tutorial
{
    class Program
    {
        int x;
        public Program(int i)
        {
            x = i;
            Console.WriteLine("Parameterized constructor is called");
        }
        void Print()
        {
            Console.WriteLine("Value of x is:" + x);
        }


        static void Main(string[] args)
        {
            Program p1 = new Program(500);
            p1.Print();
            Console.ReadLine();
        }
    }
}

OUTPUT

C# Parameterized Constructor 3

Here, Program (int i) is a parameterized constructor created with a parameter i which is an integer variable. Next, the global variable x of type integer initialized with this i. By using this constructor, an object p1 created while passing an argument 500 to the parameter i.

When we try to call the method Print(), it executes the statements inside the method by passing the argument 500 to x since x initialized with i.

C# Copy Constructor

A constructor that copies one object’s data into another object called as the copy constructor. To create multiple objects with the same values, we generally use copy constructors.

A copy constructor is a parameterized constructor that takes the same class as a parameter to it. The copy constructor syntax is

public class_name(class_name <instance of a class>)
{
     --Statements--
}

The following example shows you the way to write a copy constructor program

using System;


namespace CSharp_Tutorial
{
    class Program
    {
        int a;
        bool b;
        public Program()
        {
            Console.WriteLine("Parameterless constructor is called");
        }
        static void Main(string[] args)
        {
            Program p = new Program();
            Console.WriteLine("value of integer a is: " + p.a);
            Console.WriteLine("value of boolean b is: " + p.b);
            Console.ReadLine();
        }
    }
}

OUTPUT

C# Copy Constructor 4

copycon_Program is the C# class name. Here, the copy constructor created with a parameter obj as an instance

P2 is the instance created with the help of the copy constructor. To this constructor, the instance of a parameterized constructor, i.e., p1 passed as an argument.

Since object p1 passed as an argument to object p2, the data inside the object p1 will copied into p2 and prints the same.

C# Static constructor

A constructor defined with an access specifier static is a static constructor in C#. The constructors we have discussed until now are non-static constructors.

As we already saw when we don’t define any constructor inside a class, the non-static constructors will call implicitly. However, coming to the static constructor, if a class contains any static variables, then the compiler will call the implicit static constructor. Otherwise, we need to define a static constructor explicitly. The syntax of the C# static constructor is as shown below

static class_name()
{
   --statements—
}

Let us see an example of the C# static constructor 

using System;


namespace CSharp_Tutorial
{
    class static_Program
    {
        int x;
        static static_Program()
        {
            Console.WriteLine("static Constructor is called");


        }
        static void Main(string[] args)
        {


            Console.WriteLine("Main method is called");
            Console.ReadLine();
        }
    }
}

OUTPUT

C# Static constructors 5

When we execute the Program, since static constructor is the first to run, compiler first executes the static constructor. It then comes to the main method to execute the code in it.

C# Static constructors vs. Non-static constructors 

Static ConstructorsNon-Static Constructors
C# Static constructors are to initialize the static variables.Non-static constructors are to initialize the non-static variables.
Static constructors not called explicitly since static constructors are the first block of code to execute in every class. These constructors will get executed immediately once the class execution gets started and only once during the class’s life cycle.But coming to the non-static constructors, if no instances created, they wouldn’t execute at all. But if there are n instances created, they get executed n times.
The C# Static constructors can’t be parameterized because it cannot take parameters since it is the first block of code to get executed. Hence these constructors cannot be overloaded.Non-static constructors can be parameterized and hence can be overloaded.

The actual need of an explicit constructor in C#?

The compiler will call the implicit constructor for creating an instance of a class even if we do not define constructor explicitly. However, when we create multiple instances of a class, a class’s variables get initialize with the same values. It is because an implicit constructor is always a parameterless constructor in C# Programming language.

So if we want to assign different values of a class’s variables by creating multiple instances, then the C# parameterized constructor must define explicitly.

Finally, we can say if our class variables require some values to get executed, then explicit constructors should define to pass multiple values. So every time a new object created, we have the chance to pass new values.

using System;

namespace ConsoleApp2
{
  class Program2
  {
   public int i = 50;
  } 
}
namespace ConsoleApp2
{
  class Program
  {
    public int x;
    public Program(int a)
    {
      this.x = a;
    }
  }
}
namespace ConsoleApp2
{
  class Test
  {  
    static void Main()
    {
      Program p = new Program(1000);
      Program p1 = new Program(2000);
      Program p2 = new Program(6000);
      Console.WriteLine(p.x + " " + p1.x + " " + p2.x);
      Program2 r = new Program2();
      Program2 r1 = new Program2();
      Program2 r2 = new Program2();
      Console.WriteLine(r.i + " " + r1.i + " " + r2.i);
      Console.ReadLine();
    }
  }
}

OUTPUT

C# Static constructors 6

In the above example C# constructor program, three classes created under single namespace ConsoleApp2,

The first one is class Program2, the second one is the class Program, and the third one is the class Test. The main method has written in the Test class.

In program2, integer variable i initialized with 50 and created three instances r, r1, and r2 in class Test.

Since it doesn’t have any constructor, the compiler calls default constructor to create the instances r, r1, and r2. When we try to write i value onto the console, the same i value, i.e., 50 printed every time since the C# implicit constructor is parameterless. It cannot take any parameters to change the value.

Class Program created with a parameterized constructor Program (int a) defined in it.

So for every new instance created, the constructor will take a different integer value (i.e., 1000, 2000, 6000) since it is parameterized constructor with integer variable as a parameter.