Given the following classes:
public class Foo {
static Foo() {
Console.WriteLine("Foo is being constructed");
}
}
public class Bar {
public void ReferenceFooAsGenericTypeParameter<T>() {
Console.WriteLine("Foo is being referenced as a generic type parameter");
}
}
public class SampleClass
{
public static void Main()
{
new Bar().ReferenceFooAsGenericTypeParameter<Foo>();
}
}
The output is
Foo is being referenced as a generic type parameter
This makes sense, according to the spec:
A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
But I'm curious why the static constructor is not invoked when the type is referenced as a generic type parameter.
A static constructor does not take access modifiers or have parameters. A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced. A static constructor cannot be called directly.
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.
A static constructor does not take access modifiers or have parameters. A class or struct can only have one static constructor. Static constructors cannot be inherited or overloaded. A static constructor cannot be called directly and is only meant to be called by the common language runtime (CLR).
The constructors in Java can not be static because if the constructors are marked as static, they can not be called from the child class; thus, the child class's object will not be created. The program will not be compiled and throw a compile-time error.
Why would it need to be?
The point of the static constructor being called normally is to make sure that any state set up within the static constructor is initialized before it's first used.
Just using Foo
as a type argument doesn't make use of any state within it, so there's no need for the static constructor to be called.
You might want to try creating a static variable initializer with side effects (e.g. a method call which then prints to the console) and removing the static constructor - that can affect the timing of initialization significantly in some cases. It may trigger it here.
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