C# Variable Initializer for Class Field

See variable initializer syntax, which helps simplify programs that use multiple variables.

Variable initializers 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.ConstructorClass
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.

Example. 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 using System; class Test { string _value = Program.GetPi(); public Test() { // Simple constructor statements. Console.WriteLine("Test constructor: " + _value); } } class Program { public static string GetPi() { // This method returns a string representation of PI. Console.WriteLine("GetPi initialized"); return Math.PI.ToString(); } static void Main() { // Create an instance of the Test class. Test test = new Test(); } } Output GetPi initialized Test constructor: 3.14159265358979

Order. 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

Summary. 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-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.