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

Suppose I initialize class members as follows:

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

Does the compiler create a default constructor in this situation?

In general, I know that a constructor can initialize the value of class instance variables and can also perform some other initialization operations corresponding to the class. But in the above example, I initialized the value ialso joutside the constructor. In this situation, is the compiler still generating a default constructor? If so, what does the default constructor do?

+5
source share
3 answers

- . j. IL, .

.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
   }
+11

ECMA. 17.4.5 , , , (0 0,0 ), , .

+3

, . , , .

0

All Articles