Please enable Javascript for better experience...
An introduction to constructors in c#
By Rahul Kumar Jha | Jan 8, 2015 | In Articles | Total Views [ 4093 ]
Taged In
(2 Like)
Rate

In this article I will try to explain about constructor, its types and use in application.

Introduction

Constructor in general, is a method in class or struc with same name without any return type. When we create instance of a class or struc, constructor calls automatically. It is generally used to initialize fields and members of class or struct.

Types of Constructor

There are three main types of constructors

  • Default constructor
  • Parameterized constructor
  • Copy construtor

Apart from these, there are two more types of constructor

  • Static constructor
  • Private constructor

Let's discuss them one by one.

Default constructor

When you create instance of a class or struct without passing any parameters, it calls default constructor.

If you do not define any constructor, by default this constructor calls.

    public class ClassA
    {
        /// <summary>
        /// Default constructor
        /// </summary>
        public ClassA()
        {
            Console.WriteLine("This is default constructor...");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            //It will call default constructor
            ClassA obj1 = new ClassA();
            Console.ReadKey();
        }
    }

You cannot define default constructor explicitly for struct. It is automatically defined by compiler where constructor initialize all the fields to default values. For more information please click MSDN.

Parameterized constructor

As it is clear from its name, you can pass parameters to this constructor. This type of constructor is helpful when it is require to initialize different value for each instance created.

    public class ClassA
    {
        int _i=0;
        /// <summary>
         /// Parameterized constructor
        /// </summary>
        /// <param name="i"></param>
        public ClassA(int i)
       {
           _i = i;
           Console.WriteLine("This is parameterized constructor and you are passing _i=" + _i);
       }
    }
    class Program
    {
        static void Main(string[] args)
        {
            //It will call Parameterized constructor
            ClassA obj1 = new ClassA(5);
            // output: This is parameterized constructor and you are passing _i=5

            ClassA obj2 = new ClassA(10);
            // output: This is parameterized constructor and you are passing _i=10
            Console.ReadKey();
        }
    }

Copy construtor

It initialize its field by copying other instance. We pass an existing isntance to this constructor and it initializes with same field values.

    public class ClassA
    {
        int _i=0;
        /// <summary>
         /// Parameterized constructor
        /// </summary>
        /// <param name="i"></param>
        public ClassA(int i)
       {
           _i = i;
           Console.WriteLine("This is parameterized constructor and you are passing _i=" + _i);
       }
        /// <summary>
        /// Copy constructor
        /// </summary>
        /// <param name="obj"></param>
        public ClassA(ClassA obj)
        {
            _i = obj._i;
            Console.WriteLine("This is copy constructor and value of new _i=" + _i);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            //It will call Parameterized constructor
            ClassA obj1 = new ClassA(5);
            // output: This is parameterized constructor and you are passing _i=5

            //It will call Copy constructor and will initialize _i=5 as it is initialized in above parameterized constructor
            ClassA obj2 = new ClassA(obj1);
            // output: This is copy constructor and value of new _i=5
            Console.ReadKey();
        }
    }

After this let's see other constructors i.e Static and Private

Static construtor

This constructor calls first before any other constructor by default. It initializes only one time at the time when other instances are created for a class due to its static nature. You cannot call it explicitly.

You cannot add access modifier with this type of constructor.

    public class ClassA
    {
        int _i = 0;
        static ClassA()
        {
            Console.WriteLine("This is static constructor and it is called automatically when you initialized first instance.");
        }

        /// <summary>
        /// Default constructor
        /// </summary>
        public ClassA()
        {
            Console.WriteLine("This is default constructor...");
        }
        /// <summary>
         /// Parameterized constructor
        /// </summary>
        /// <param name="i"></param>
        public ClassA(int i)
       {
           _i = i;
           Console.WriteLine("This is parameterized constructor and you are passing _i=" + _i);
       }
        public ClassA(ClassA obj)
        {
            _i = obj._i;
            Console.WriteLine("This is copy constructor and value of new _i=" + _i);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            //Static constructor will call automatically even if we did not initialized it. We cannot directly call static constructor
            ClassA obj2 = new ClassA(5);
            ClassA obj3 = new ClassA(obj2);

            Console.ReadKey();
        }
    }

Private constructor

This type of constructor is created when you need to restrict user to create instance of a class.

You cannot create instance of a class if it has private constructor of that type, say default constructor.

    public class ClassWithPrivateConstructor
    {
        static int _i = 5;
        private ClassWithPrivateConstructor()
        {
            Console.WriteLine("This is private constructor and you cannot create object of this class...");
        }
        public static int Value
        {
            get { return _i; }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            //It will through compile time error. ClassWithPrivateConstructor() is inaccessible due to its protection level.
            //ClassWithPrivateConstructor obj = new ClassWithPrivateConstructor();
            Console.Write("Property value is:" + ClassWithPrivateConstructor.Value);
            Console.ReadKey();
        }
    }

Hope this can help you. Please like the article and put your comments.

Share this

About the Author

Rahul Kumar Jha
Rahul Kumar Jha
Founder, Developer dotnet-concept.com

Public profile: user/profile/99900001


Has working experience in different phases of Software Development Life Cycle (SDLC) in CMS, Gaming, Health Care and Financial Services domain using Agile pattern. Working experience in Design patterns, ASP.NET, MVC, ANGULAR, ANGULAR JS, Windows application, WCF, ADO.NET, SQL Server and Test Driven Development (TDD) environment with JQuery, JavaScript, N-Unit, Entity Frameworks, LINQ, Code Refactoring and Business Objects Models.

User's Comments


 
Please SignUp/Login to comment...

Or comment as anonymous...
* Name
* Email ID
Comment
 
 
 
 
 
 
Sponsors