Create object, C# default or parameterized constructor call?

Question Description: In C#, between default and parameterized constructor, which is called if you create an object of a class? For example if class is A, on object creation A obj = new A ().

Answer: No constructor will be called but compiler error on statement A obj = new A (). If we have parameterized constructor only in a class. For example

class A
{  
    //parameterized constructor
    public A(int a) { Console.WriteLine("Parameterize Constructor"); }   
}

As if we write any constructor in a class, compiler does not provide its default constructor.

So, if we want to create an object of a class without parameter i.e. A obj = new A (). We have to write an empty constructor in the class.

class A
{
    //empty constructor
    public A() { Console.WriteLine("Empty Constructor"); }

    ////parameterized constructor
    public A(int a) { Console.WriteLine("Parameterize Constructor"); }   
}
class Program
{
    static void Main(string[] args)
    {
        //Empty constructor will be called.
        A a = new A();       
    }   
}


NOTES: Rule: If you provide any constructor in a class i.e. empty or parameterized constructor to a class then compiler will not provide its default constructor in C#.

Related Posts