Search code examples
c#genericsstatic-constructor

Why isn't a static constructor invoked on a class used as a generic type parameter?


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.


Solution

  • 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.