Varto
Varto

Reputation: 51

Is a constructor always present in a class?

When I create class without constructor and with constructor, the IL code doesn't change. Am I wrong in thinking that there is always constructor present?

namespace Test13
{
    class Human
    {

    }
}    

In the following IL code, the line -

IL_0001: call instance void [System.Runtime]System.Object::.ctor()

makes a call to a constructor without declaring constructor.

.class private auto ansi beforefieldinit
  Test13.Human
    extends [System.Runtime]System.Object
{

  .method public hidebysig specialname rtspecialname instance void
    .ctor() cil managed
  {
    .maxstack 8

    // [11 9 - 11 23]
    IL_0000: ldarg.0      // this
    IL_0001: call         instance void [System.Runtime]System.Object::.ctor()
    IL_0006: nop

    // [12 9 - 12 10]
    IL_0007: nop

    // [14 9 - 14 10]
    IL_0008: ret

  } // end of method Human::.ctor
} // end of class DecompilationLearn.Human

If someone can clear this up to me, thanks.

Upvotes: 0

Views: 161

Answers (3)

atiyar
atiyar

Reputation: 8305

In short, yes.

If you don't provide any constructor yourself, the compiler will add a public default (parameterless) one during compilation, which will be generated in IL code.

When you create an object of a class, you call the constructor of that class after the new keyword -

Human human = new Human();

Therefore, any class that you can create an object of, must have a constructor. That is why, if you don't provide a constructor to Human class, the compiler provides one to make sure you can instantiate the class, as mentioned in the documentation here -

If you don't provide a constructor for your class, C# creates one by default that instantiates the object and sets member variables to the default values ...

For static classes there's an exception (as mentioned by @JonSkeet in the comments) - static classes cannot have a constructor with any access modifier. That's because you are not allowed to create an object of a static class.

The IL code you mentioned is not making -

a call to constructor without declaring constructor

Instead, it is calling the constructor of the base class (System.Object) of Human, and that call is taking place inside the Human constructor that the compiler has generated for you.

Upvotes: 2

Ramakrishnan
Ramakrishnan

Reputation: 5436

If you don't define a constructor in c#, the C# compiler automatically creates one public parameterless constructor in the class.

Constructors - MSDN

Upvotes: 2

Thomas Weller
Thomas Weller

Reputation: 59305

As you have observed correctly and MSDN confirms in the section "Parameterless constructors":

If you don't provide a constructor for your class, C# creates one by default

Upvotes: 2

Related Questions