How to ensure that a static constructors is called without calling any member
Asked Answered
V

1

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.

Vacuva answered 4/5, 2013 at 16:8 Comment(5)
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.Dight
@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.Vacuva
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).Dight
@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.Deckhand
@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.Vacuva
B
29

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

RuntimeHelpers.RunClassConstructor(typeof(YourType).TypeHandle);
Basis answered 4/5, 2013 at 16:11 Comment(2)
Does it only run the constructor once?Dight
@RobertHarvey, yes, it runs the static constructor only once, even if you call it multiple times.Basis

© 2022 - 2024 — McMap. All rights reserved.