Is a C# class without constructor possible?

Answer: Yes, C# class without constructor is possible. In fact, we can have a class without any constructor in C#. If we don’t declare any constructors in a class, the compiler automatically provides a public parameter less constructor. And it is ok to instantiate  the class without constructor.

In the below C# code example program, we don’t have any constructor in the class Person.

class Person
{  
    //This class has no constructor
    public void getPersonProfile()
    {
        Console.WriteLine("Base class:getPersonProfile() have no constructor");
    }
}

class Program
{
    static void Main(string[] args)
    {
        //Create object of person
        Person p = new Person();
        p.getPersonProfile();
    }
}

Abstract class without constructor in C#

Compiler provides protected parameter less constructor for an abstract class C# program. We know that in an inheritance hierarchy, if we create an object of a child class, first base class and then child class constructor will be called. You may wish to read Constructor and destructor call order in a class in C#

Hence, if base class does not contains any constructor, compiler provides protect parameter less constructor.

In the below C# program example, the class Person is an abstract class, and the Employee class has been derived from it. If we created the object of the child class Employee, first base class default protected constructor then derived class constructor will be called.

[If you want to get an idea about abstract class, then read this interview question on abstract class in C# , that is,  what feature to use to have common behaviors in one class and force other classes to implement others behaviors.]

abstract class Person
{  
    //This class has no constructor
    public void getPersonProfile()
    {
        Console.WriteLine("Base class:getPersonProfile()method - have no constructor");
    }
}
class Employee : Person
{
    //child class constructor
    public Employee()
    {
        Console.WriteLine("Derived Class Employee constructor");
    }

}
class Program
{
    static void Main(string[] args)
    {
        //Create object of person
        Person p = new Employee();
        p.getPersonProfile();
    }
}

Output:

Derived Class Employee constructor
Base class:getPersonProfile() method – have no constructor

Related Posts