Static Constructors – What is the output of the C# code?

class A
{
  public A(string text)
  {
    Console.WriteLine(text);
  }
}
 
class B
{
  static A a1 = new A(“a1”);
 
  A a2 = new A(“a2”);
 
  static B()
  {
    a1 = new A(“a3”);
  }
 
  public B()
  {
    a2 = new A(“a4”);
  }
}
 
class Program
{
  static void Main(string[] args)
  {
    B b = new B();
  }
}
Before any code of the type B gets executed, its static constructor will be invoked first. It initializes static data fields and then executes statements inside the static constructor. Therefore, it prints a line of “a1”, and then another line of “a3”.
When the execution flow reaches the statement B b = new B(), the ordinary constructor is invoked. It initializes its data fields first and then the statements in its constructor method, so it prints a line of “a2”, and then another line of “a4”.
Output:
a1
a3
a2
a4
Advertisements

One thought on “Static Constructors – What is the output of the C# code?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s