I’ve recently moved a project I’m working on from .NET 3.5 to .NET 4. I’m using C#, Managed C++ and Unmanaged C++.
In one of my Managed C++ (interop) I’m having a static constructor:
public ref class StaticPool : public BaseStaticPools
{
public:
static StaticPool()
{
InitializePools();
}
static Poolable^ Dequeue()
{
return (Poolable^)Dequeue(Poolable::typeid);
}
private:
static void InitializePools()
{
BaseStaticPools::CreatePool(Poolable::typeid);
}
};
In .NET 3.5 once Dequeue() had been called for the first time it would trigger the static initialization, which runs the static constructor. Once I moved to .NET 4.0, the static constructor was never called.
I know there have been changes in static initializations in .NET 4.0, but according to all I read it should work fine.
In .NET, type initializers may only be called the first time a field is accessed. This is controlled by the
[BeforeFieldInit]attribute.I filed a bug report, which is only available to beta testers, despite being marked "Public".
Here’s the explanation from Microsoft, which you may find helpful: