Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't the static constructor of the parent class called when invoking a method on a nested class?

Given the following code, why isn't the static constructor of "Outer" called after the first line of "Main"?

namespace StaticTester
{
    class Program
    {
        static void Main( string[] args )
        {
            Outer.Inner.Go();
            Console.WriteLine();

            Outer.Go();

            Console.ReadLine();
        }
    }

    public static partial class Outer
    {
        static Outer()
        {
            Console.Write( "In Outer's static constructor\n" );
        }

        public static void Go()
        {
            Console.Write( "Outer Go\n" );
        }

        public static class Inner
        {
            static Inner()
            {
                Console.Write( "In Inner's static constructor\n" );
            }

            public static void Go()
            {
                Console.Write( "Inner Go\n" );
            }
        }
    }
}
like image 737
Ryan Ische Avatar asked Apr 13 '10 12:04

Ryan Ische


People also ask

Why static nested class is required?

A static class is a class that is created inside a class, is called a static nested class in Java. It cannot access non-static data members and methods. It can be accessed by outer class name. It can access static data members of the outer class, including private.

How are static constructors executed in Parent Child C#?

It is invoked automatically. The user has no control on when the static constructor is executed in the program. A static constructor is called automatically. It initializes the class before the first instance is created or any static members declared in that class (not its base classes) are referenced.

What is the main difference between an inner class and a static nested class in Java?

1) First and most important difference between Inner class and nested static class is that Inner class require instance of outer class for initialization and they are always associated with instance of enclosing class. On the other hand nested static class is not associated with any instance of enclosing class.

What is a static nested class in Java?

In Java a static nested class is essentially a normal class that has just been nested inside another class. Being static, a static nested class can only access instance variables of the enclosing class via a reference to an instance of the enclosing class.


1 Answers

Your question is answered by section 10.12 of the specification, which states:

The execution of a static constructor is triggered by the first of the following events to occur within an application domain:

• An instance of the class type is created.

• Any of the static members of the class type are referenced.

Since you've done neither of those two things, the ctor is not executed.

like image 157
Eric Lippert Avatar answered Sep 25 '22 22:09

Eric Lippert