SoFunction
Updated on 2025-03-06

How to understand the constructor of C# class through IL

Preface

We know that when calling the constructor, C# will first initialize the fields and properties in the class. So, the question is, why do the fields and properties in the class be initialized before calling the constructor? Let's unveil the constructor through ildasm.

The C# code that needs to be decompiled is as follows:

class CtorTester
{
 private string _name;
 private int _age = 10;

 public int Age { get; set; } = 20;

 public CtorTester()
 {
  _name = "Name";
 }
}

Use the ildasm tool to IL decompile the .exe file. Here is the IL code for the constructor:

.method public hidebysig specialname rtspecialname 
  instance void .ctor() cil managed
{
 // Code size  36 (0x24)
 .maxstack 8
 IL_0000: ldarg.0 //Press the parameter indexed to 0. IL_0001: ldc. 10 //Press int 10 to stack. IL_0003: stfld  int32 _011_Ctor.CtorTester::_age // Assign the value at the top of the stack to the second value in the stack, that is, _age=10, and complete the initialization operation of the field _age. IL_0008: ldarg.0
 IL_0009: ldc. 20
 IL_000b: stfld  int32 _011_Ctor.CtorTester::'<Age>k__BackingField' //Complete the initialization operation of attribute Age. IL_0010: ldarg.0
 IL_0011: call  instance void [mscorlib]::.ctor() //Calling the constructor of the base class Object IL_0016: nop
 IL_0017: nop
 IL_0018: ldarg.0
 IL_0019: ldstr  "Name"
 IL_001e: stfld  string _011_Ctor.CtorTester::_name //Complete the assignment operation of field _name, that is, "_name = "Name";" in the constructor IL_0023: ret
} // end of method CtorTester::.ctor

Through parsing the IL code of the constructor, it is found that C# will inline the initialization of fields and attributes into the constructor when compiling. This is why we execute the field and attribute initialization code before calling the constructor.

The storage path of the tool:
C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin

References

IL instruction description: /zh-cn/dotnet/api/?
redirectedfrom=MSDN&view=netframework-4.7.2#fields

Summarize

The above is the entire content of this article. I hope that the content of this article has certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.