开发者

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 e开发者_运维知识库xample, 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?


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
   }


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜