Home
Search
C# Variable InitializerSee variable initializer syntax, which helps simplify programs that use multiple variables.
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.
Program We see the Test class, which uses a variable initialization. The Program class provides Main().
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(); } }
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.
IL
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.
Home
© 2007-2021 sam allen. see site info on the changelog