Home
C#
Variable Initializer
This page was last reviewed on Jun 1, 2021.
Dot Net Perls
Variable initializer. This syntax helps simplify programs. It enables us to directly assign a field at the class level. We can simplify constructors.
Generated code. A variable initializer results in the C# compiler generating appropriate code. The code is placed at the beginning of all constructor method bodies.
Constructor
class
An example. Here we see a variable initializer. When you have a field in a class, you can assign that field directly inside the class declaration.
Detail We see the Test class, which uses a variable initialization. The Program class provides Main().
Detail The Test class is constructed and allocated upon the managed heap. The constructor calls GetPi and stores its result.
Detail This method call was inserted at the top of the constructor in the compiled code.
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(); } }
GetPi initialized Test constructor: 3.14159265358979
Order. Let's inspect the .ctor() member. We see that the initialization of the field _value was inserted at the top of the constructor body.
Intermediate Language
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.
A 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jun 1, 2021 (edit).
Home
Changes
© 2007-2024 Sam Allen.