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

No comments:

Post a Comment