C# Constructors

Constructor is one type of method which automatically invoked when class instance created.

Constructor name same as class name.

It’s mainly use for initialize  and set the value for class properties of new object. If we create class without constructor, then automatically default constructor generate for that class. That’s means always one constructor exist in class.

In c#, Class contains more than one constructor in one class with different parameters. Constructor doesn’t return any value so no need to add return type. not even write void while creating constructor.

Syntax:

public class User
{
// Constructor
public User()
{
// Your Custom Code
}
}

In c#, Different types of constructor, those are,

  • Default Constructor
  • Parametrized Constructor
  • Static Constructor
  • Private Constructor
  • Copy Constructor

Let’s discuss each constructor step by step with examples.

Default Constructor

Whenever we create any constructor without any parameter, it’s call as s default constructor.

using System;

namespace ConstructorDemo
{
    public class Student
    {
        public string Name { get; set; }
        public string Gender { get; set; }

        // Default Constructor
        public Student()
        {
            Name = "Jay";
            Gender = "Male";
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            /// The constructor will be called automatically once the instance of the class created
            Student student = new Student(); 
            Console.WriteLine(student.Name);
            Console.WriteLine(student.Gender);
            Console.WriteLine("\nPress Enter Key to Exit..");
            Console.ReadLine();
        }
    }
}

When you execute the above program, will get the result below

If you observe the above result, constructor method has called automatically and initialized the parameter values after creating an instance of our class

Parametrized Constructor

If we create constructor with parameter then it’s called Parametrized constructor.

using System;

namespace ConstructorDemo
{
    public class Student
    {
        public string Name { get; set; }
        public string Gender { get; set; }
        // Default Constructor
        public Student(string name, string gender)
        {
            Name = name;
            Gender = gender;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            /// The constructor will be called automatically once the instance of the class created
            Student student = new Student("Jay","Male"); //Parametrized constructor
            Console.WriteLine(student.Name);
            Console.WriteLine(student.Gender);
            Console.WriteLine("\nPress Enter Key to Exit..");
            Console.ReadLine();
        }
    }
}

When you execute the above program, will get the result below

Here, constructor method has called automatically and initialized the parameter values after creating an instance of our class with the required parameters.

In c#, We can overload the constructor by using same name with different parameters.

Static Constructor

It’s invoked only once, irrespective of numbers of instance. Automatically called before first instance.

using System;

namespace ConstructorDemo
{
    public class Student
    {
        static Student()  // Default Constructor
        {
            Console.WriteLine("I am Static Constructor");
        }

        public Student()  // Default Constructor
        {
            Console.WriteLine("I am public Constructor");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Student student = new Student(); 
            Student student1 = new Student();
            Console.WriteLine("\nPress Enter Key to Exit..");
            Console.ReadLine();
        }
    }
}

When you execute the above program, will get the result below,

Here, for the first instance of a class, both static and default constructors execute. For the second instance of a class, only default constructor has been executed.

Private Constructor

If we didn’t use any access modifier to define the constructor, then by default, it will treat it as private.

It is useful in classes that contain only static members.

If class contain one or more private constructor then can’t create instance of that class.

using System;

namespace ConstructorDemo
{
    public class Student
    {
        private Student()  // Default Constructor
        {
            Console.WriteLine("I am private Constructor");
        }
        public static string Name { get; set; }

        public Student(string name)
        {
            Name = name;
        }

    }
    class Program
    {
        static void Main(string[] args)
        {
            //Student student = new Student(); //throw exception due to protection level.

            Student student = new Student("Jay");
            Console.WriteLine(Student.Name); //access class property direct
            Console.WriteLine("\nPress Enter Key to Exit..");
            Console.ReadLine();
        }
    }
}

If you uncomment the commented line (Student  student = new Student();), then it will throw an error because the constructor is private, so it won’t allow you to create an instance for that class.

When you execute the above program, will get the result below,

Submit a Comment

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

Subscribe

Select Categories