C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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.
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
Thus: This syntax will have no unique effect on execution and is purely syntactic sugar in the language.