Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 676
Martin Mulder Avatar asked May 04 '13 16:05

Martin Mulder


People also ask

Can we call static constructor from non-static constructor?

yes we can have static constructor inside a non-static class. Yes, it can.

How do you call a static constructor?

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.

How can we pass parameters to static constructors?

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).

Can non-static constructor call static methods?

Static method cannot cannot call non-static methods. Constructors are kind of a method with no return type.


1 Answers

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

RuntimeHelpers.RunClassConstructor(typeof(YourType).TypeHandle);
like image 95
Thomas Levesque Avatar answered Sep 28 '22 09:09

Thomas Levesque