views:

72

answers:

1

I'm calling the static ctor of a class using this code:

Type type;
System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(type.TypeHandle);

Can this cause the cctor to be run twice?

+2  A: 

No, it runs the static constructor only once, even if you call RunClassConstructor twice. Just try ;)

using System.Runtime.CompilerServices;
...

void Main()
{
    RuntimeHelpers.RunClassConstructor(typeof(Foo).TypeHandle);
    RuntimeHelpers.RunClassConstructor(typeof(Foo).TypeHandle);
    Foo.Bar();
}

class Foo
{
    static Foo()
    {
        Console.WriteLine("Foo");
    }

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

This code prints :

Foo
Bar

Thomas Levesque
Is that true even if I call RunClassConstructor, _then_ use the class for the first time (which would usually cause the cctor to run)? And is that guaranteed? The MSDN does not provide any information.
mafutrct
Ah, ok, so it works in practice. Now if only some official paper would state that this is not going to be changed in the future...
mafutrct
BTW, I tested the code above with .NET 4.0, and there has been a few changes to the way types are initialized in .NET 4.0 (see Jon Skeet's blog post : http://msmvps.com/blogs/jon_skeet/archive/2010/01/26/type-initialization-changes-in-net-4-0.aspx). So you might want to try it in 3.5
Thomas Levesque
Yes, but I'd really like an official paper to make sure it's not going to be changed randomly. That's the only concern left.
mafutrct
IMHO, it's unlikely that they will ever make such a breaking change...
Thomas Levesque