Nishant Kumar
Nishant Kumar

Reputation: 6083

In C#, is a default constructor generated when class members are initialized?

Suppose I initialize members of a class like this:

class A 
{
    public int i=4;
    public double j=6.0;
}

Does the compiler generate a default constructor in this situation?

In general, I know that a constructor may initialize the value of class instance variables and may also perform some other initialization operations appropriate for the class. But in the above example, I have initialized the value of i and j outside of a constructor. In this situation, does the compiler still generate a default constructor? If so, what does the default constructor do?

Upvotes: 5

Views: 329

Answers (3)

Jim Brissom
Jim Brissom

Reputation: 32919

You can read these things up in the official ECMA language standard. Chapter 17.4.5 talks about this specific issue, basically stating that fields will be default-initialized with whatever default value the type has (0 or 0.0, respectively in your case), and afterwards the value initialization will be executed in the order that they are declared in the source file.

Upvotes: 3

Brian Rasmussen
Brian Rasmussen

Reputation: 116401

The compiler still generates a default constructor in this case. The constructor handles the initialization of i and j. If you look at the IL this is evident.

.class auto ansi nested private beforefieldinit A
   extends [mscorlib]System.Object
{
   .method public hidebysig specialname rtspecialname instance void .ctor() cil managed
   {
      .maxstack 8
      L_0000: ldarg.0 // pushes "this" onto the stack
      L_0001: ldc.i4.4 // pushes 4 (as Int32) onto the stack
      L_0002: stfld int32 TestApp.Program/A::i // assigns to i (this.i=4)
      L_0007: ldarg.0 // pushes "this" onto the stack
      L_0008: ldc.r8 6 // pushes 6 (as Double) onto the stack
      L_0011: stfld float64 TestApp.Program/A::j // assigns to j (this.j=6.0)
      L_0016: ldarg.0 // pushes "this" onto the stack
      L_0017: call instance void [mscorlib]System.Object::.ctor() // calls the base-ctor
      /* if you had a custom constructor, the body would go here */
      L_001c: ret // and back we go
   }

Upvotes: 11

Tim Carter
Tim Carter

Reputation: 600

the variable initialisation you have above will be run first. Then anything you have in your constructor will be run after.

Upvotes: 0

Related Questions