This syntax helps simplify programs. It enables us to directly assign a field at the class
level. We can simplify constructors.
A variable initializer results in the C# compiler generating appropriate code. The code is placed at the beginning of all constructor method bodies.
Here we see a variable initializer. When you have a field in a class
, you can assign that field directly inside the class
declaration.
class
, which uses a variable initialization. The Program
class
provides Main()
.class
is constructed and allocated upon the managed heap. The constructor calls GetPi
and stores its result.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
Let's inspect the .ctor()
member. We see that the initialization of the field _value was inserted at the top of the constructor body.
class
declarations in the C# language.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.