Generic Base Static Constructor behavior

Hi all,

I have found some weird behavior with a class that derives from a genericized base class when the base class has static methods, etc.

Here is some sample code:

public class TemplatedBase<TDerived>
{
static TemplatedBase()
{
Console.WriteLine("TemplatedBase cctor");
}

public static void TemplatedBaseStaticMethod()
{
Console.WriteLine("TemplatedBaseStaticMethod");
}
}

public class Derived : TemplatedBase<Derived>
{
static Derived()
{
Console.WriteLine("Derived cctor");
}

public
Derived()
{
Console.WriteLine("Derived ctor");
}
}

class Program
{
static void Main(string[] args)
{
Derived.TemplatedBaseStaticMethod();
Console.WriteLine("----");
Derived d = new Derived();
Console.WriteLine("End");
}
}

Output
TemplatedBase cctor
TemplatedBaseStaticMethod
----
Derived cctor
Derived ctor
End

Expected Output
TemplatedBase cctor
Derived cctor
TemplatedBaseStaticMethod
----
Derived ctor
End

I was kind of hoping a static constructor should be called before any instances are created or static methods called. So why is Derived cctor not called until we do new Derived()

TemplatedBaseStaticMethod() is an (inherited) static method of Derived - so surely the static ctor for Derived should kick in

If I was doing TemplatedBase<Something>.TemplatedBaseStaticMethod(), then I'd accept this behavior, but I'm specifically deriving.

I'm confused.. can anyone shed some light on this

James



Answer this question

Generic Base Static Constructor behavior

  • PeterPan1120

    If you have a look at the underlying IL, you will understand why. IL does not have a concept of accessing static members through a derived class, this is a C# concept.

    Underneath, the following is actually happening:



    TemplatedBase<Derived>.TemplatedBaseStaticMethod();
    Console.WriteLine("----");
    Derived d = new Derived();
    Console.WriteLine("End");



  • Generic Base Static Constructor behavior