C / C++ / C#

  1. Home
  2. Computing & Technology
  3. C / C++ / C#

C# Tutorial - About Value Types and Reference Types

By David Bolton, About.com

8 of 10

Static Constructors and Field Initializers Continued

C# supports a constructor initializer list syntax not dissimilar to that of C++ except you can only initialize the base instance (perhaps adding in parameters) or the current instance class (through the use of the word this) Adding this code in below, and explicitly calling the base class does not affect the program as this is what the compiler does behind the scenes.
public c() : base()
{
  Console.WriteLine("Constructor c") ;
}
You can even add in a call to another constructor, as in below. The single parameter instance constructor is called before the default constructor.
public c(int v)
{
  stcint = v;
}

public c() : this(1)
{
  Console.WriteLine("Constructor c") ;
}
The use of base and this apply only to instances and not static classes. There is no instance in a static class.

Static Constructors and Initializers So why were the static constructors and initializers and the instance initializers called in the order c, b ,a and not the same order as the instance constructors? Because that is the order that the classes are accessed. The first class created was c. What actually happens is this.

  1. Static Field Initializers are executed. These might be needed in the static constructor.
  2. Static Constructor is called.
  3. The instance initializer is called.
  4. The base class is accessed, repeating steps 1-3.

Some Simple Rules to Remember

  • Field Initializers are called before Constructors.
  • Static Initializers and Constructors are called once before any instances are constructed.
  • Statics are called (in a class hierarchy) in the order that classes are used.
  • Instances are constructed in a hierarchy starting with the ancestor class.

On the next page : More about Using This and Base

Explore C / C++ / C#

About.com Special Features

C / C++ / C#

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C# / C Sharp
  5. Learn C Sharp
  6. Static Constructors and Field Initializers Continued

©2009 About.com, a part of The New York Times Company.

All rights reserved.