Common Type System—Field Initialization


Jump to: navigation, search
Visual C# Tutorials
.NET Framework Tutorials

Common Type System

© 2006 Wiley Publishing Inc.

Field Initialization (Language Feature)

If you use inline initialization for instance fields, the code for that initialization ends up being copied by the C# compiler to all constructors, which don’t delegate to another constructor on the type using the this keyword. For example, consider this type:

class FieldInitExample
{
   int x = 5;
   int y;
 
   public FieldInitExample() : this(5)
   {
   }
 
   public FieldInitExample(int y)
   {
      this.y = y;
   }
}

The int x = 5 line is actually copied to the first few statements of the constructor, which takes an integer argument. It doesn’t get copied to the default constructor because that constructor just delegates to the other overload, which would lead to redundant stores to the x field. The resulting IL is as if you wrote:

class FieldInitExample
{
   int x;
   int y;
 
   public FieldInitExample() : this(5)
   {
   }
 
   public FieldInitExample(int y)
   {
      this.x = 5;
      this.y = y;
   }
}

Static field initialization is handled nearly identically, with the caveat that static class constructors are used instead of instance constructors. The CctorExample type from above could have been written as follows, while keeping the same semantics as before:

class CctorExample
{
   static DateTime classLoadTimestamp = DateTime.Now;
}


Previous_Page_.gif Next_Page_.gif





Personal tools
Share this page