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.
yes we can have static constructor inside a non-static class. Yes, it can.
A static constructor cannot be called directly and is only meant to be called by the common language runtime (CLR). It is invoked automatically. The user has no control on when the static constructor is executed in the program. A static constructor is called automatically.
A static constructor is called automatically to initialize the class before the first instance is created, so we can't send it any parameters. You cant pass parameters to Static Constructors, because you cannot access any non-static member outside of a static method (constructor too).
Static method cannot cannot call non-static methods. Constructors are kind of a method with no return type.
You can use the RuntimeHelpers.RunClassConstructor
method (assuming that I correctly understood what you were trying to do...)
RuntimeHelpers.RunClassConstructor(typeof(YourType).TypeHandle);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With