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" );
}
}
}
}
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With