C# Variable Initializer for Class FieldThis C# program shows variable initializer syntax. This syntax lets you simplify programs.
simplify programs. This syntax enables you to directly assign a field at the class level. This results in the C# compiler generating appropriate code at the beginning of all constructor method bodies.Constructor
Tip: This feature exists to allow shorter source text for class declarations in the C# language.
Info: The resulting code is equivalent to having the variable initialized at the top of all constructor method bodies.
In this code example we demonstrate the execution of the variable initializer syntax form. When you have a field in a class, you can assign that field directly inside the class declaration.
Program: We see the Test class, which uses a variable initialization syntax form, and the Program class which provides the Main entry point.
First: The Test class is constructed and allocated upon the managed heap. The constructor calls GetPi and stores its result.
GetPi: This method call was inserted at the top of the constructor in the compiled code.
C# program that uses variable initializer in class
string _value = Program.GetPi();
// Simple constructor statements.
Console.WriteLine("Test constructor: " + _value);
public static string GetPi()
// This method returns a string representation of PI.
static void Main()
// Create an instance of the Test class.
Test test = new Test();
Test constructor: 3.14159265358979
Let's address the order of execution of the statements and examine the compiled intermediate language. If we inspect the .ctor() member, we see that the initialization of the field _value was inserted at the top of the constructor body.IL DisassemblerIL
We saw a variable initializer. This is a syntax form that allows you to assign a field to the result of an expression or method invocation. The C# compiler generates code at the top of all relevant constructors.
Thus: This syntax will have no unique effect on execution and is purely syntactic sugar in the language.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to firstname.lastname@example.org.