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

Given the following code, why not the static "Outer" constructor 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 static constructor\n" );
        }

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

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

            public static void Go()
            {
                Console.Write( "Inner Go\n" );
            }
        }
    }
}
+5
source share
4 answers

In the case of nested classes, if the nested class never refers to the static members of its outer scope, the compiler (and CLR) are not required to call the static constructor of this outer class.

If you want to make the static constructor work, just add the code to the inner type that reads the field or property of the outer type.

# Jon Skeet - . - # In Depth, ... .

+5

10.12 , :

:

• .

• .

, ctor .

+6

Outer.Inner , "Outer".

+3

A static initializer is launched only when the contained class is used for the first time.

When calling Outer.Inner, you are not using it at all Outer, since it Outer.Inneris a different type than Outer. Thus, the static initializer in Outerwill not start.

0
source

All Articles