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

7 of 10

Static Constructors and Field Initializers

Download Example 7.

Example 7 shows three Classes a,b c such that a is the ancestor class and b is derived from a and c from b. All three classes have a default static constructor as well as a default instance constructor and two fields, one static, one instance.

All fields have initializers on them which just return an int via a call to a static function that outputs the name of the field. This example shows the order in which fields are initialized and constructors (both static and instance) are called. The output is shown below. Fields are named to help reveal their nature- cint (int in class c) and stcint, a static int in class c etc.

GetValue for stcint
Static Constructor c
GetValue for cint
GetValue for stbint
Static Constructor b
GetValue for bint
GetValue for staint
Static Constructor a
GetValue for aint
Constructor a
Constructor b
Constructor c
Forgetting about initializers for now, it's interesting to note that static constructors are called in the opposite order to instance constructors. All of this happens when this line is executed.
c obj = new c();
Instance constructors are responsible for initializing their part of the instance and this is always in the order from base to the bottom derived class. The instance of b inherits from a so a is initialized then b then c. The compiler adds a hidden call to call the derived classes instance constructor. So c() calls b() which calls a().

On the next page : Static Initializers and Constructors continued

Explore C / C++ / C#

About.com Special Features

Build Your Own Website

Step-by-step advice on how to do everything from choosing a Web host to promoting your content. More >

Connect Your Home Computers

Easy ways to connect two computers for networking purposes. More >

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

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

All rights reserved.