14

I have a class with a static constructor.

I want the static constructor to be called without calling or using any of its members, but only if the constructor has not been called already.

I tried using reflection. With reflection I can invoke the static constructor (many times), but I cannot find out if it has already been called before.

How do I do this?

EDIT
This is not only ONE class I am talking about, it could be more. Lets say, all classes marked with a special attribute.

Martin Mulder
  • 12,642
  • 3
  • 25
  • 54
  • 1
    Set a flag. You would only need to run a static constructor if you are setting some static state, so set that state, and just see if it is set if the constructor is run again. – Robert Harvey May 04 '13 at 16:09
  • @Robert: I need it to be a generic solution. I do not know in advance how many classes and which classes. FLagging it won't help since .NET will not set that flag when he calls the constructor. – Martin Mulder May 04 '13 at 16:13
  • You got me curious now. Why do you feel it necessary to run the constructor *before* any members are called, if that's what it's going to do anyway? (the static constructor will get called just prior to executing the first method or property call. Any static state is irrelevant until the first method or property is touched). – Robert Harvey May 04 '13 at 16:13
  • @RobertHarvey: Presumably it's due to side effects, e.g. registering the type in some central factory. I normally think of this sort of thing as something to be avoided if at all possible, but sometimes it *can* be the best of various ugly alternatives. – Jon Skeet May 04 '13 at 16:16
  • 1
    @Robert: Jon guessed it correctly. I am trying some plug-in system. If a DLL is present in the plug-in folder it has to be loaded. Classes marked with a [Register]-attribute are registered at a centralized type. Other types marked as [AutoInitialize] are initialized automatically so they can start listening to events, or such things. – Martin Mulder May 04 '13 at 16:18

1 Answers1

29

You can use the RuntimeHelpers.RunClassConstructor method (assuming that I correctly understood what you were trying to do...)

RuntimeHelpers.RunClassConstructor(typeof(YourType).TypeHandle);
Michael Liu
  • 52,147
  • 13
  • 117
  • 150
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758