How can I run a static constructor?
Solution 1
The other answers are excellent, but if you need to force a class constructor to run without having a reference to the type (i.e. reflection), you can use RunClassConstructor
:
Type type = ...;
System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(type.TypeHandle);
Solution 2
Just reference one of your static fields. This will force your static initialization code to run. For example:
public class MyClass
{
private static readonly int someStaticField;
static MyClass() => someStaticField = 1;
// any no-op method call accepting your object will do fine
public static void TouchMe() => GC.KeepAlive(someStaticField);
}
Usage:
// initialize statics
MyClass.TouchMe();
Solution 3
The cctor (static constructor) will be called whenever one of the following occurs;
- You create an instance of the class
- Any static member is accessed
- Any time before that, if
BeforeFieldInit
is set
If you want to explicitly invoke the cctor, assuming you have other static members, just invoke/access them.
If you are not doing anything very interesting in your cctor, the compiler may decide to mark it BeforeFieldInit
, which will allow the CLR the option to execute the cctor early. This is explained in more detail here: http://blogs.msdn.com/davidnotario/archive/2005/02/08/369593.aspx
Solution 4
Also you can do this:
type.TypeInitializer.Invoke(null, null);
Solution 5
Extending Fábio's observations, the following short and complete test program exposes the JIT-sensitive details of TypeAttributes.BeforeFieldInit
behavior, comparing .NET 3.5 to the latest version (as of late 2017) .NET 4.7.1, and also demonstrates the potential hazards for build type variations within each version itself.[1]
using System;
using System.Diagnostics;
class MyClass
{
public static Object _field = Program.init();
public static void TouchMe() { }
};
class Program
{
static String methodcall, fieldinit;
public static Object init() { return fieldinit = "fieldinit"; }
static void Main(String[] args)
{
if (args.Length != 0)
{
methodcall = "TouchMe";
MyClass.TouchMe();
}
Console.WriteLine("{0,18} {1,7} {2}", clrver(), methodcall, fieldinit);
}
};
Below is the console output from running this program in all combinations of { x86, x64 } and { Debug, Release }. I manually added a delta symbol Δ
(not emitted by the program) to highlight the differences between the two .NET versions.
.NET 2.0/3.5
2.0.50727.8825 x86 Debug
2.0.50727.8825 x86 Debug TouchMe fieldinit
2.0.50727.8825 x86 Release fieldinit
2.0.50727.8825 x86 Release TouchMe fieldinit
2.0.50727.8825 x64 Debug
2.0.50727.8825 x64 Debug TouchMe fieldinit
2.0.50727.8825 x64 Release
2.0.50727.8825 x64 Release TouchMe fieldinit
.NET 4.7.1
4.7.2556.0 x86 Debug
4.7.2556.0 x86 Debug TouchMe fieldinit
4.7.2556.0 x86 Release Δ
4.7.2556.0 x86 Release TouchMe Δ
4.7.2556.0 x64 Debug
4.7.2556.0 x64 Debug TouchMe fieldinit
4.7.2556.0 x64 Release
4.7.2556.0 x64 Release TouchMe Δ
As noted in the intro, perhaps more interesting than the version 2.0/3.5 versus 4.7 deltas are the differences within the current .NET version, since they show that, although the field-initialization behavior nowadays is more consistent between x86
and x64
than it used to be, it's still possible to experience a significant difference in runtime field initialization behavior between your Debug
and Release
builds today.
The semantics will depend on whether you happen to call a disjoint or seemingly unrelated static method on the class or not, so if doing so introduces a bug for your overall design, it is likely to be quite mysterious and difficult to track down.
Notes
1. The above program uses the following utility function to display the current CLR version:
static String clrver()
{
var s = typeof(Uri).Assembly.Location;
return FileVersionInfo.GetVersionInfo(s).ProductVersion.PadRight(14) +
(IntPtr.Size == 4 ? " x86 " : " x64 ") +
#if DEBUG
"Debug ";
#else
"Release";
#endif
}
![mafu](https://i.stack.imgur.com/GQA4L.jpg?s=256&g=1)
mafu
Updated on March 24, 2020Comments
-
mafu over 4 years
I'd like to execute the static constructor of a class (i.e. I want to "load" the class) without creating an instance. How do I do that?
Bonus question: Are there any differences between .NET 4 and older versions?
Edit:
- The class is not static.
- I want to run it before creating instances because it takes a while to run, and I'd like to avoid this delay at first access.
- The static ctor initializes
private static readonly
fields thus cannot be run in a method instead.
-
Marc Gravell about 14 yearsNot quite true... it can run later: msmvps.com/blogs/jon_skeet/archive/2010/01/26/…
-
mafu about 14 yearsThis fails in my case because there are
static readonly
fields. -
Ray about 14 yearsI am constantly amazed by the number of obscure language features which I have never heard of, will probably never intentionally use, but which will probably bite me in the ass because I am not aware of them...
-
mafu about 14 yearsI want to run it earlier because it takes a long time (see edited question).
-
Ray about 14 yearsmakes sense - create a "load()" method on your static class and call it whenever you want to. Just be sure to using locking and flags (or whatever) if necessary so it doesn't get loaded multiple times.
-
mafu about 14 yearsSee comments to Ray's answer about the dummy method.
-
mafu about 14 years@Ray: A load method can't initialize readonly fields though. :\
-
Ray about 14 yearsAs Mick Jagger once said: "you can't always git what you want" - how about using private static members with public static 'get' properties?
-
mafu about 14 years@Ray: Possible workaround, but I specifically asked this question because I wanted to avoid that.
-
Ray about 14 yearsCool - I like Fabio's no-op method idea. Reading any property (even to throw away the value) would work too.
-
mafu about 14 yearsDoes that run the static ctor? The class does not have a public constructor. Also, is this safe in that it does not cause a ctor to run twice, possibly?
-
Gary Linscott about 14 yearsYes, it runs the static ctor. It is also safe, the CLR will only let the static ctor be executed once.
-
Ruben about 14 yearsIndeed, this method is explicitly provided for compiler writers to ensure deterministic initialization: blogs.msdn.com/cbrumme/archive/2003/04/15/51348.aspx
-
mafu about 14 yearsInteresting. But cbrumme does not seem to explicitly state that the cctor gets called executed once, or did I miss that? I do like this solution, but I'd like to get this guaranteed before I accept.
-
tomosius over 8 yearsThank You! This answer provided the only way for me to solve my problem. I am implementing a Java-like enum pattern using abstract Enumeration<T> class. It has a collection called values which stores a list of all enumerated instances of the derived enumeration class. The collection is inherited by each deriving class, so each derived class has an accessible list of it's enumerated values. Also neat is that the derived class does not need to explicitly handle any of this because the values list is retrieved by a static property in Enumeration<T> class. The only issue I had was this. Solved!
-
mafu over 7 yearsI'm a bit confused. Suppose you have two derived classes (with static ctors) and call a static method in the base class (which also has a static ctor). The static ctor of which derived class should be called then? Given this reasoning, the behavior you describe sounds not strange.
-
Glenn Slayden over 6 years@Ray To avoid further downvotes, please add a prominent warning or amendment to the text of this answer to clarify that it contains an incorrect assertion.
-
Glenn Slayden over 6 yearsYour answer is the same as @Ray's but his posted a couple minutes earlier. Unfortunately, like his, your info is also misleading. Besides the problem mentioned in the previous (OP's) comment, the second part of your proposal wouldn't work for
static class MyClass { }
(which had been available since 2006 at that point). -
Glenn Slayden over 6 years@mafu I think he's talking about the reverse situation: it is true that any invocation of a
static _ctor
("type initializer") of some derived class in no way entails the invocation of the type initializer of its base class, and this may seem counterintuitive at casual first glance. Knowing more about the .NET, CTS, and CIL design and capabilities quickly dispels the intuition, however, and it becomes natural to understand the existing behavior... mainly because it becomes easy to imagine the out-of-control edge cases if it were otherwise! -
Glenn Slayden over 6 years@tomosius Yes, this solution is correctly marked as such by the OP. The existing ECMA-335 design is essentially necessary because finding a workable topological sort for the (possibly cyclic) graph of dependencies entailed by static constructors alone ("type initializers" in .NET-speak) is expensive at best and provably impossible at worst. Since that graph, being entirely disjoint from the proper type hierarchy in .NET, is obscurely specific, the whole enterprise is justifiably judged “not worth it.”
-
Glenn Slayden over 6 years@mafu
RunClassConstructor
is a nop if the class initializer has already been invoked. Otherwise, calling that helper counts as the "one-and-only" invocation. It's exactly what you requested in your question. Do note that the discrepancies I document in my answer (which address your "bonus" inquiry) may still apply, unless you can be sure that you are able to explicitly invokeRunClassConstructor
before those problems have an opportunity to arise. -
Glenn Slayden over 5 yearsTo summarize, the best way to avoid problems is to call
RuntimeHelpers.RunClassConstructor(t.TypeHandle)
as eagerly, liberally, and/or often as you like. It's the only way to (attempt to) explicitly control inter-Type dependencies (via sequencing), and always guarantee that noType
initializer will ever be called more than once. This includes properly handling cyclical cases, such aType
explicitly requesting—or implicitly demanding—("re-")initialization within the execution scope of of its own initialization (i.e., before its static constructor has exited). -
Glenn Slayden over 5 yearsMy previous comment entails that as far as the CLR is concerned, a
Type
is considered initialized at the beginning of its initializer method body. That is, it's already "initialized" immediately prior to executing the first line of its static constructor. Since a type initializer can call static methods on its own type—and/or exterior methods that do the same—that entire call-graph is excluded from the stronger guarantee that all calls into a type's static methods will always see it "fully-initialized," i.e., where the execution scope of the static constructor has ended/exited. -
Glenn Slayden about 5 yearsNice; who knew?!! I wonder how the overall performance of this compares to
RuntimeHelpers.RunClassConstructor
... -
Wai Ha Lee over 4 yearsMarc Gravell's link is now dead and can be found on Jon Skeet's site here: codeblog.jonskeet.uk/2010/01/26/…
-
Wai Ha Lee over 4 yearsNote that
TypeInitializer.Invoke
will allow multiple calls to the static constructor, whereasRuntimeHelpers.RunClassConstructor
guards against that. -
Eugenio Miró almost 4 yearsThis was the solution I was looking for so I can reconfigure an static class when setting a configuration value on a test, nice catch!
-
Eugenio Miró almost 4 yearsI found this answer to be the one I used because it allowed me to re-execute the constructor even if it was executed before, and that was needed because an static class was being used in several tests and the initialization used ConfigurationManager to set a value, only one test needed to reset that vale but not the others.
-
Brondahl over 3 yearsWarning! In addition to allowing you to re-invoke the static constructor (yay!) it also allows for the possibility of ending up with NESTED invocations of that static constructor (=:0) which is prevented if you use
RunClassConstructor
or allow the RunTime to initialise it for you. For safety you might want to consider aReset()
method that callsRunClassConstructor()
and thenTypeInitializer.Invoke()
, in order to get something that will always re-run it cleanly, whether or not it's run previously.