Brief idea on constructor in .net

Monday, 9 May 2016

Brief idea on constructor in .net

Constructor:- 

A Constructor is a special method in a class/struct with the same name as that of class/struct without any return type, used to initialize fields
and members of a class/struct; A Constructor is called automatically when object of class created.We can use constructor overloading also in the program. 

In case of parent child relationship ,when we make the object of child class, then child class constructor is called and base class default constructor is executed.
  class Program
     {
         static void Main(string[] args)
               {
             Derive ObjDr= new Derive ("abcd");     //parameterised constructor of Derive class is called which takes one aguments and default
                                                           //constructor of BaseClass class is called.
             Console.WriteLine(ObjDr.BcName);      // default constructor of BaseClass class is called which takes no aguments
             Console.WriteLine(ObjDr.DrName);     //default constructor of Derive class is called which takes no aguments
             Console.ReadLine();
         }
     }
     public class BaseClass
     {
         public string BcName;

         public BaseClass ()
         {
             BcName= "mithun";
             Console.WriteLine("Default constructor of BaseClass Class");
         }
         public BaseClass (string aa)
         {
             BcName= aa;
             Console.WriteLine("Paramerterise constructor of BaseClass Class");
         }
     }
     public class Derive: BaseClass
         public string DrName;
         public Derive()
         {
             DrName= "noha";
             Console.WriteLine("default constuctor of Derive");
         }
         public Derive (string ram)
         {
             DrName= ram;
             Console.WriteLine("paramerised constructor of Derive");
         }
     }
 }

OutPut :Default constructor of BaseClass Class
        paramerised constructor of Derive
  mithun
 abcd

If we want to call a specific constructor of the base class through derive class, then we can specify the "base" keyword with child class constructor.
In this case the above Derive class paramerised constructor format will be :

         public Derive(string ram): base(ram)
         {
             address = ram;
             Console.WriteLine("paramerised constructor of Derive");
         }

OutPut :Paramerterise constructor of BaseClass Class
        paramerised constructor of Derive
  abcd
 abcd

Type of Constructors:-

Static Constructor

A static constructor has the same name as the class name but preceded with the static keyword; it will be called at the time of class load.
• No access specifier for static constructor.
• Static constructor will not return anything.
• Static constructor will accept only static members.
• Static constructor will call at the time of class loading.
• Static constructor will not allow overloading, so there is no parameterized static constructor.

    class StaticExam
    {
        public static string country_nm = "India";
        // Static Constructor
        static StaticExam()
        {
            Console.WriteLine("Static Constructor Call...");
            Console.WriteLine("{0} is coming from static member",country_nm );
        }
        // Parametarized constructor
        public StaticExam(string country_name)
        {
            Console.WriteLine("Parametarized constructor Call");
            Console.WriteLine("Parametarized Constructor Country name  {0}", country_name);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            // Creating object for StaticExam class by passing parameter
            // This will called parametarized constructor which matches
            StaticExam pObj = new StaticExam("India");
            Console.Read();
        }
    }

Output :Static Constructor Call...
 India is coming from static member
 Parametarized constructor Call
 Parametarized Constructor Country name India

Please check the above code,which will show you ones you create the object of the staticExam class using Parameterised constructor first static constructor will call
then the parameterised constructor will invoke.

Private Constructor:- 

To use a private constructor we should have main function in the same class, generally we will define constructors in different classes so defining
private constructors is not that much useful.

In many situation, we may wish to define some utility classes that contain only static member such classes are never required to instantiate objects.
Creating objects using such classes may be prevented by adding private constructor to the class. Read this example

class PrivateExam
    {
        // Default private constructor
        private PrivateExam()
        {
            Console.WriteLine("Default Private Constructor...");
         
       }
        static void Main(string[] args)  // This line is very important, because this function is written within the same class.
        {
            // Creating object for PrivateExam class
            // This will called default private constructor
            PrivateExam obj = new PrivateExam();
            Console.Read();
        }
    }

Copy Constructor:- 

A copy constructor creates an object by copying variables from another object.  Since C# does not provided a copy constructor ,we must provide it
ourselves if we wish to add this feature to the class.
Non Static Constructor:-
Non static member are those member which is dynamically changes over the program. Non Static constructor(Instinct Constructor) is called whenever object
of the class is created.


Default Constructor:-

1         A Constructor with no parameter is called Default Constructor.
2         Default Constructor is called by compiler when no arguments are passed to New operator while creating an object of class or struct.
            If there is no constructor in a Non-Static class, a Public Default Constructor is provided by compiler so that a class can be instantiated.
        A Struct cannot have an explicit Default Constructor (We cannot define an explicit Default Constructor in astruct), but it is always provided by compiler to initialize each field of struct to its default value.

Difference between Static and Non static Constructor:-

Static Constructor
and Non static Constructor
 Static  Constructor  is called automatically by CLR when class is loaded in first time in memory        
Instinct Constructor (non static constructor) is called whenever the object of the class is created.


 We can pass parameter in in Non static Constructor
We cannot pass parameter  to the Static Constructor.
 There can be only one static Constructor within the  class.
There can be more than one Non static Constructor  within the  class.
 We can not use any Access specifier in static constructors
We can use within Non static Constructors

Reminder on Constructor Chaining

1. A constructor can make a call to another constructor of the same class or of base class;
2. Since one constructor can invoke another, this sometimes can cause execution of multiple                   constructors and is referred to as Constructor chaining;
3. If class is not derived from any other class, below would be the chain:
1. Static Constructor
2. Instance Constructor
4. If a class is derived from any other class, below would be the chain:
1. Derived Static Constructor
2. Base Static Constructor
3. Base Instance Constructor
4. Derived Instance Constructor

Some Interview question are shown below:

1.Can constructors  be inherited ?
    No.

2.How can you call a base class constructor from a child class ?
   Child class can call base class constructor by using the keyword base.

3.In which order  constructor is called in inheritance ?
    If Class B inherits Class A ,when you create object of Class B then Class B contructor is called first then Class A construcotr is called.
  eg-
     class ClassA
{
    public ClassA()
    {
        Console.WriteLine("i am class A");
    }
}

class ClassB:ClassA
{
    public ClassB()
    {
        Console.WriteLine("i am class B");
    }
}

output- i am class B
              i am class A

4.How do you call one constructor from another in the same class ?
      By using this keyword. eg-
      class numbers
      {
                public numbers() {
                 }

               public numbers(int a):this(){
              }
       }


5.When you create an object of the above class which constructor is called first ?
 When you instantiate the above class first overloaded constructor is called and then the default one is called.
6.Does memory gets allocated when constructor is called ?
       Yes using new operator.


7. what happens when you instantiate an object ?
      When you create instance of  a class using new operator foll happens-
       New memory is allocated
       instance is created on heap
       reference is created on stack and passed on the the instantiated object.

8.What is default access modifier of constructor ?
       Private
9.Which of the following statements is correct about the C#.NET code snippet given below?
namespace IndiabixConsoleApplication
{
    class Sample
    {
        public int func()
        {
            return 1;
        }
        public Single func()
        {
            return 2.4f ;
        }
    }
    class Program
    {
        static void Main(string[ ] args)
        {
            Sample s1 = new Sample();
            int i;
            i = s1.func();
            Single j;
            j = s1.func();
        }
    }
}
A. func() is a valid overloaded function.
B.Overloading works only in case of subroutines and not in case of functions.
C.func() cannot be considered overloaded because: return value cannot be used to distinguish between two overloaded functions.
D.The call to i = s1.func() will assign 1 to i.
E.The call j = s1.func() will assign 2.4 to j.
Answer: Option C

10.How do I call one constructor from another in C#? 
You use : base (parameters) or : this (parameters) just before the actual code for the constructor, depending on whether you want to call a constructor
in the base class or in this class.

11.Can you prevent a class from being instantiated?
Yes, a class can be prevented from being instantiated by using a private constructor as shown in the example above on private constructor segment.


12.Can a class or a struct have multiple constructors?
Yes, a class or a struct can have multiple constructors. Constructors in csharp can be overloaded.

Can a child class call the constructor of a base class?
Yes, a child class can call the constructor of a base class by using the base keyword as shown in the example at the begining of constructor.



13.If a child class instance is created, which class constructor is called first - base class or child class?
When an instance of a child class is created, the base class constructor is called before the child class constructor. An example is shown below.



14.Will the following code compile?
using System;
namespace TestConsole
{
  class BaseClass
  {
    public BaseClass(string str)
    {
      Console.WriteLine(str);
    }
  }
  class ChildClass : BaseClass
  {
    public ChildClass()
    {
      Console.WriteLine("I am a child class constructor");
    }
    public static void Main()
    {
      ChildClass CC = new ChildClass();
    }
  }
}

No, the above code will not compile. This is because, if a base class does not offer a default constructor, the derived class must make an
explicit call to a base class constructor by using the base keyword as shown in the example below.

using System;
namespace TestConsole
{
  class BaseClass
  {
    public BaseClass(string str)
    {
      Console.WriteLine(str);
    }
  }
  class ChildClass : BaseClass
  {
    //Call the base class contructor from child class
    public ChildClass() : base("A call to base class constructor")
    {
      Console.WriteLine("I am a child class constructor");
    }
    public static void Main()
    {
      ChildClass CC = new ChildClass();
    }
  }
}