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 class are sent to it using constructors. The syntax of the C# constructor is shown below.

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

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

A programmer must define a constructor explicitly inside a class. Otherwise, while executing, the C# compiler creates a constructor by default. We call it an implicit 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 only.

Let us see how a C# default constructor will call to initialize the variables when it’s 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 a C# constructor to initialize those variables but asked to print their values of them.

While executing, 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 is not defined inside the class. When we try to call it, then the C# compiler will call the parameterless constructor by default. Hence the one called by the compiler, which was not defined explicitly, is called the implicit constructor.

Types of Constructors in C#

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

  • Default or parameterless.
  • Parameterized
  • Copy.
  • Static.

Default parameterless constructor in C#

Any method that doesn’t take any values (or) that doesn’t have any parameters will call a parameterless or default constructor.

The Syntax of the C# default or the parameterless constructor.

using System;

public Class_name ()
{
       --statements--
}

Let us see the same C# example program that executes previously with a small change of defining the 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();
        }
    }
}
C# Default Constructor 2

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

Program() is a parameterless constructor that we 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 defines with the parameters (or) the one that takes values said to be a parameterized constructor. The 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

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();
        }
    }
}
C# Parameterized Constructor 3

Here, C# Program (int i) is a parameterized constructor created with parameter i, an integer variable. Next, the global variable x of type integer initializes with this i. By using this constructor, an object p1 is 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 is initialized with i.

C# Copy Constructor

The one that copies one object’s data into another object is called the C# copy constructor. We use copy constructors to create multiple objects with the same values.

A copy constructor is parameterized 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();
        }
    }
}
C# Copy Constructor Example 4

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

P2 is the instance will create with the help of the copy constructor. For this, 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 object p1 will copy into p2 and print the same.

C# Static constructor

The one defined with an access specifier static is a static constructor in C#. The ones 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-statics 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 static ones 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();
        }
    }
}
C# Static constructors 5

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

C# Static vs. Non-static constructors 

StaticNon-Static
C# Static constructors are to initialize the static variables.Non-static constructors are to initialize the non-static variables.
These are not called explicitly since static constructors are the first block of code to execute in every class. These constructors will be executed immediately once the class execution starts and only once during the class’s life cycle.But coming to the non-static constructors, if no instances are created, they won’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.They can be parameterized and hence can be overloaded.

The actual need for 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 it explicitly. However, when we create multiple class instances, a class’s variables will initialize with the same values. It is because an implicit constructor is always parameterless in C# Programming language.

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

Finally, we can say if our class variables require some values will execute, then explicit constructors should define to pass multiple values. So every time a new object creates, 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();
    }
  }
}
Explicit Example 6

In the above example constructor program, three classes are created under a 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 been 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 the default one 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 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 with an integer variable as a parameter.

Categories C#