Home > Software engineering >  What is the difference between the parameterless constructor with no members VS default constructor
What is the difference between the parameterless constructor with no members VS default constructor

Time:02-03

class Constructor
{
    Constructor()
    {
    }

    static void Main()
    {
        Constructor obj = new Constructor();
    }
}

class Compiler
{
    Compiler obj1 = new Compiler();
}

In the first program I created a constructor with no members and in the second program I'm not created any constructor so the compiler creates a default constructor so what's the difference between them in c#

CodePudding user response:

Reference: Microsoft docs - Constructors

"...classes without constructors are given a public parameterless constructor by the C# compiler in order to enable class instantiation."

Cases when you do need to write a parameterless constructor:

  1. When you have other constructors defined in the class.
  2. When you want to use a different protection level for your parameterless constructor.

CodePudding user response:

There are other problems (see below) in the code shown, but in general there is no difference between an empty parameterless constructor you create vs. an empty parameterless constructor the compiler creates. It's possible they result in slightly different compiled code, but for all intents and purposes they do the same thing.


Other problems in the code shown...

This will result in an infinite recursion any time you try to create an instance of it:

class Compiler
{
    Compiler obj1 = new Compiler();
}

And this constructor is not the same as the compiler-default one because class members are private by default:

class Constructor
{
    Constructor()
    {
    }

    static void Main()
    {
        Constructor obj = new Constructor();
    }
}
  • Related