Why we use constructor in c# | All about Constructor

What is Constructor in c#


Constructors are the special type of methods that invoked when the first object of class is created. The name of constructor is same as class name. If you do not use an access modifier with the constructor it will still be public by default.


c# class constructor example




Example:

using System;

 public class Employee   //  class
{
     public Employee()   //Constructor
     {

     }

}

Some characteristics of constructors:


  1. Constructors are always public.
  2. Constructor can be overloaded
  3. Constructors do not have any return type.
  4. Constructor is automatically declared by CLR, whenever the class is instantiated.
  5. A constructor can have any number of parameters .

Why we use constructor in c#

Constructor is used to object initialization and memory allocation of the class.
Use to initialize private fields’ value of the class whenever instance or object of class is created.

Why we can not inherit constructor

Constructors are not members, so they are not inherited by derive classes, but the constructor of the base class can be invoked from the derive class.


Behaviour of constructors in case of inheritance

The role of constructor in case of inheritance, if we create an object of derive class it first call the base class constructor then derive class constructor. It means that first the base class to be initialize then derive class. If you want to see how the base class is initialize first, may you have to put debugger and do find the step by step process by using F11 key.

C# class constructor example



using System;

public class Employee   //  class
{
    public int age;
    public string name;
    public Employee()   //Constructor
    {

    }
}
class MainClass : Employee
{
    static void Main(string[] args)
    {
        MainClass obj = new MainClass();
        obj.age = 12;
        obj.name = "Jhon";
    }
}

Put debugger and see what happen next

c# class constructor example






1 Comments

  1. excellent one ...as compared to many sites and bloggers

    ReplyDelete

Post a Comment

Post a Comment

Previous Post Next Post