How can I find a static class initializer in C# using reflection? Even GetMembers()
invoked on the type of a class does not seem to provide that information.
Asked
Active
Viewed 131 times
0

Regis May
- 3,070
- 2
- 30
- 51
2 Answers
2
Use type.TypeInitializer
to find it.

Daniel A. White
- 187,200
- 47
- 362
- 445
-
While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/10241257) – Michael Dunlap Nov 18 '15 at 03:14
-
1@MichaelDunlap - even *without* the link, it does answer "*How can I find a static class initializer?*". – Wai Ha Lee Nov 18 '15 at 04:14
-
Thank you, that answers my question. One additional question: By experimenting with `TypeInitializer` it seems that as soon as I have at least one static (read only) variable within a class a static initializer seems to be generated automatically. I guess there is no way to distinguish between an explicitely defined initializer within a class and an implicitely defined one by the compier? – Regis May Nov 18 '15 at 07:20
-
@RegisMay i'm not sure. i didn't see anything on `ConstructorInfo` that would give a clue to that information. Perhaps that would be best asked as a new post. – Daniel A. White Nov 18 '15 at 11:31
1
I found a way to call static constructor by using reflection. Is this what you are looking for.
Type myClass = typeof (MyClass); myClass.TypeInitializer.Invoke(null,null);

Majed
- 53
- 8
-
Thank you, yes. Both answers are correct. The property `TypeInitializer` is what I am looking for. – Regis May Nov 18 '15 at 07:10