Constructors in C#

Constructors in C# with Examples

In this article, I am going to discuss the different types of Constructors in C# with examples. Please read our previous article before proceeding to this article where we discussed how to create class and objects in C# with examples. As part of this article, we are going to discuss the following pointers in detail with examples.

  1. What is a Constructor in C#?
  2. Rules to follow while creating Constructors in C#.
  3. What a Constructor can have in C#?
  4. Can we define a method with the same class name in C#?
  5. How many types of constructors are there in C#.Net?
  6. What is Default Constructor in C#?
  7. When do we need to provide the constructor explicitly?
  8. What is User-Defined Default Constructor in C#?
  9. When should we define a parameterized constructor in a class?
  10. What is a Parameterized Constructor in C#?
  11. How many constructors can be defined in a class in C#?
  12. What is Copy Constructor in C#?
  13. Understanding Static Constructor in C#.
  14. Can we initialize non-static data members within a static constructor in C#?
  15. Is it possible to initialize static data fields within a non-static constructor in C#?
  16. Can we initialize static data fields in both static and non-static constructor?
  17. What is Private Constructor in C#?
  18. Understanding constructor overloading in C#?
What is a Constructor in C#?

In simple words, we can define the constructors in C# are the special types of methods of a class that automatically executed whenever we create an instance (object) of that class. The Constructors in C# are responsible for two things. One is the object initialization and the other one is memory allocation. The role of the new keyword is to create the object.

Rules to follow while creating the constructor in C#:
  1. The constructor name should be the same as the class name.
  2. It should not contain return type even void also.
  3. The constructor should not contain modifiers.
  4. As part of the constructor body return statement with value is not allowed.
What a Constructor have in C#?
  1. It can have all five accessibility modifiers.
  2. The constructor can have parameters.
  3. It can have throws clause it means we can throw an exception from the constructor.
  4. The constructor can have logic, as part of logic it can have all C#.NET legal statements except return statement with value.
  5. We can place return; in the constructor.
Syntax:

Constructors in C#

Example: Program to show the use of the constructor in C#.
namespace ConstructorDemo
{
    class Program
    {
        Program()
        {
            Console.WriteLine("This is Constructor");
        }
        public static void Main(string[] args)
        {
            Program p = new Program();
            Console.WriteLine("Main method");
            Console.ReadKey();
        }
    }
}

OUTPUT:

Constructors in C#

Can we define a method with the same class name in C#?

No, it is not allowed to define a method with the same class name in C#. It will give you a compile-time error.

How many types of constructors are there in C#.net?

There are five types of constructor in C#, they are as follows

  1. Default Constructor
  2. Parameterized Constructor
  3. Copy Constructor
  4. Static Constructor
  5. Private Constructor

Let’s discuss each of these constructors in detail with examples.

Default Constructor in C#:

The Constructor without parameter is called a default constructor. Again the default constructor is classified into two types.

  1. System-defined default constructor
  2. User-defined default constructor
What is System Defined Default Constructor in C#?

As a programmer, if you are not defined any constructor explicitly in your program, then by default the system will provide one constructor at the time of compilation. That constructor is called a default constructor. The default constructor in C# will assign default values to the data members (non-static variables). As this constructor is created by the system this is also called as system-defined default constructor.

Let us see an example for a better understanding of the system-defined default constructor in C#.

namespace ConstructorDemo
{
    class Employee
    {
        int eid, eage;
        String eaddress, ename;
        public void Display()
        {
            Console.WriteLine("\nemployee id is:  " + eid);
            Console.WriteLine("employee name is:  " + this.ename);
            Console.WriteLine("employee age is:  " + this.eage);
            Console.WriteLine("employee address is:  " + eaddress);
        }
    }
    class Test
    {
        static void Main(string[] args)
        {
            Employee e1 = new Employee();
            Employee e2 = new Employee();
            e1.Display();
            e2.Display();
            Console.ReadKey();
        }
    }
}

Note: The point that you need to keep in mind is that the System will only provide the default constructor if as a programmer you are not defined any constructor explicitly.

When do we need to provide the constructor explicitly?

If you want to execute some logic at the time of object creation, that logic may be object initialization logic or some other useful logic, then as a developer, we must provide the constructor explicitly.

What is User-Defined Default Constructor in C#?

The constructor which is defined by the user without any parameter is called as user-defined default constructor in C#. This constructor does not accept any argument but as part of the constructor body, you can write your own logic.

Let’s understand user-defined default constructor in C# with an example:

namespace ConstructorDemo
{
    class Employee
    {
        int eid, eage;
        string eaddress, ename;
        public Employee()
        {
            this.eid = 100;
            eage = 30;
            this.ename = "Pranaya";
            eaddress = "MUMBAI";
        }
        public void Display()
        {
            Console.WriteLine("employee id is:  " + eid);
            Console.WriteLine("employee name is:  " + this.ename);
            Console.WriteLine("employee age is:  " + this.eage);
            Console.WriteLine("employee address is:  " + eaddress);
        }
    }
    class Test
    {
        public static void Main(string[] args)
        {
            Employee e1 = new Employee();
            Employee e2 = new Employee();
            e1.Display();
            e2.Display();
            Console.ReadKey();
        }
    }
}

OUTPUT:

User Defined Default Constructor in C#

The drawback of the above user-defined default constructor is every instance (i.e. object) of the class will be initialized (assigned) with the same values. That means it is not possible to initialize each instance of the class with different values.

When should we define a parameterized constructor in a class?

If you want to initialize the object dynamically with the user given values then you need to use the parameterized constructor. The advantage is that you can initialize each object with different values.

What is Parameterized Constructor in C#?

The developer given constructor with parameters is called as the parameterized constructor in C#. With the help of a Parameterized constructor, we can initialize each instance of the class with different values. That means using parameterized constructor we can store a different set of values into different objects created to the class.

Let us understand the parameterized constructor in C# with one example.

namespace ConstructorDemo
{
    class Employee
    {
        int eid, eage;
        String eaddress, ename;
        public Employee(int id, int age, string name, string address)
        {
            this.eid = id;
            this.eage = age;
            this.ename = name;
            this.eaddress = address;
        }
        public void Display()
        {
            Console.WriteLine("employee id is:  " + eid);
            Console.WriteLine("employee name is:  " + this.ename);
            Console.WriteLine("employee age is:  " + this.eage);
            Console.WriteLine("employee address is:  " + eaddress);
        }
    }
    class Test
    {
        static void Main(string[] args)
        {
            Employee e1 = new Employee(101, 30, "Pranaya", "Mumbai");
            Employee e2 = new Employee(101, 28, "Rout", "BBSR");
            e1.Display();
            e2.Display();
            Console.ReadKey();
        }
    }
}

OUTPUT:

Parameterized Constructor in C#

How many constructors can be defined in a class in C#?

In C#, within a class, we can define any number of constructors. But the most important point that you need to remember is that each and every constructor must have a different signature. Different signature means the number, type and parameter order should be different. So in a class, we can define one no-argument constructor plus ‘n’ number of parameterized constructors in C#.

What is Copy Constructor in C#?

The constructor which takes a parameter of the class type is called a copy constructor. This constructor is used to copy one object data into another object. The main purpose of the copy constructor is to initialize a new object (instance) with the values of an existing object (instance).

Let us understand the copy constructor in C# with one example:

namespace ConstructorDemo
{
    class Employee
    {
        int eid, age;
        string address, name;
        public Employee()
        {
            Console.WriteLine("ENTER EMPLOYEE DETAILS");
            Console.WriteLine("Enter the employee id");
            this.eid = int.Parse(Console.ReadLine());
            Console.WriteLine("Enter the employee age");
            this.age = int.Parse(Console.ReadLine());
            Console.WriteLine("Enter the employee name");
            this.name = Console.ReadLine();
            Console.WriteLine("Enter the employee address:");
            this.address = Console.ReadLine();
        }
        public Employee(Employee tempobj)
        {
            this.eid = tempobj.eid;
            this.age = tempobj.age;
            this.name = tempobj.name;
            this.address = tempobj.address;
        }
        public void Display()
        {
            Console.WriteLine();
            Console.WriteLine("Employee id is:  " + this.eid);
            Console.WriteLine("Employee name is:  " + this.name);
            Console.WriteLine("Employee age is:  " + this.age);
            Console.WriteLine("Employee address is:  " + this.address);
        }
    }
    class Test
    {
        static void Main(string[] args)
        {
            Employee e1 = new Employee();
            Employee e2 = new Employee(e1);
            e1.Display();
            e2.Display();
            Console.ReadKey();
        }
    }
}

OUTPUT:

Copy Constructors in C#

Understanding Static Constructor in C#:

In C#, it is also possible to create a constructor as static and when we do so, it is called Static Constructor. The static Constructor in C# will be invoked only once. There is no matter how many numbers of instances (objects) of the class are created, it is going to be invoked only once and that is during the creation of the first instance (object) of the class.

The static constructor is used to initialize the static fields of the class. You can also write some code inside the static constructor which is going to be executed only once. The static data members in C# are created only once even though we created any number of objects.

Points to Remember while creating Static Constructor in C#:
  1. There can be only one static constructor in a class.
  2. The static constructor should be without any parameter.
  3. It can only access the static members of the class.
  4. There should not be any access modifier in static constructor definition.
  5. If a class is static then we cannot create the object for the static class.
  6. Static constructor will be invoked only once i.e. at the time of first object creation of the class, from 2nd object creation onwards static constructor will not be called.

Let us understand Static Constructor with an example.

namespace ConstructorDemo
{
    class Example
    {
        int i;
        static int j;
        public Example()
        {
            i = 100;
        }
        static Example()
        {
            j = 100;
        }
        public void Display()
        {
            Console.WriteLine("value of i : " + i);
            i++;
            Console.WriteLine("value of j : " + j);
            j++;
        }
    }
    class Test
    {
        static void Main(string[] args)
        {
            Example e1 = new Example();
            e1.Display();
            e1.Display();
            Example e2 = new Example();
            e2.Display();
            e2.Display();
            Console.ReadKey();
        }
    }
}

OUTPUT:

Static Constructor in C# with Examples

Can we initialize non-static data members within a static constructor in C#?

It is not possible to initialize non-static data members within a static constructor, it raises a compilation error. Have a look at the following example.

static Example()
{
        int = 101;//not allowed
        j = 100;
}
Can we initialize static data fields within a non-static constructor in C#?

Yes, you can initialize static data members within a non-static constructor but after then they lose their static nature. Consider the following example:

public Example()
{
         i = 100;
         j = 100; //allows but j lose its static nature
}
Can we initialize static data fields in both static and non-static constructor?

Yes, we can initialize static data fields in both static and non-static constructors but static data fields lose their static nature. For example

public Example()
{
       i = 100;
       j = 100; //allows but j looses its static nature
}

static Example()
{
       j = 105; //allowed
}

What is Private Constructor in C#?

In C#, it is also possible to create a constructor as private. The constructor whose accessibility is private is known as a private constructor. When a class contains a private constructor then we cannot create an object for the class outside of the class. So, private constructors are used to creating an object for the class within the same class. Generally, private constructors are used in Remoting concept.

Let us see an example for understanding private constructor

namespace ConstructorDemo
{
    class Program
    {
        private Program()
        {
            Console.WriteLine("this is private constructor");
        }
        static void Main(string[] args)
        {
            Program p = new Program();
            Console.WriteLine("main method");
            Console.ReadKey();
        }
    }
}

What is constructor overloading?

When we define multiple constructors within a class with different parameter types, number and order then it is called as constructor overloading.

Let us see an example for a better understanding of the Constructor Overloading in C#.

namespace ConstructorDemo
{
    class ConstructorOverloading
    {
        int x;
        public ConstructorOverloading()
        {
            this.x = 10;
        }
        public ConstructorOverloading(int x)
        {
            this.x = x;
        }
        public void Display()
        {
            Console.WriteLine("the value of x:{0}", x);
        }
    }
    class Test
    {
        static void Main(string[] args)
        {
            ConstructorOverloading obj1 = new ConstructorOverloading();
            ConstructorOverloading obj2 = new ConstructorOverloading(20);
            obj1.Display();
            obj2.Display();
            Console.ReadKey();
        }
    }
}

OUTPUT:

Constructors Overloading in C#

That’s it for today. In the next article, I am going to discuss the Destructors in C# with examples. Here, in this article, I try to explain the different types of Constructors in C# with examples. I hope now you understood the need and use of different types of constructors.

2 thoughts on “Constructors in C#”

  1. i have not understood below tow point

    Can we initialize non-static data members within a static constructor in C#?
    It is not possible to initialize non-static data members within a static constructor, it raises a compilation error. Have a look at the following example.

    static Example()
    {
    int = 101;//not allowed
    j = 100;
    }
    Can we initialize static data fields within a non-static constructor in C#?
    Yes, you can initialize static data members within a non-static constructor but after then they lose their static nature. Consider the following example:

    public Example()
    {
    i = 100;
    j = 100; //allows but j lose its static nature

Leave a Reply

Your email address will not be published. Required fields are marked *