I'm calling the static ctor of a class using this code:
Type type;
System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(type.TypeHandle);
Can this cause the cctor to be run twice?
A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed only once. It is called automatically before the first instance is created or any static members are referenced.
When a data member is shared among different instances it is imperative that data should be consistent among all the instances of the class. And also there is no way to call static constructor explicitly. Therefore the purpose of having a parameterized static constructor is useless.
Also, you can have a static constructor in a static class or a non-static class. A static constructor is used to initialize the static members of a class. The static constructor of a class is invoked the first time a static member of the class is accessed.
That's why you can see in the output that Static Constructor is called first. Times of Execution: A static constructor will always execute once in the entire life cycle of a class. But a non-static constructor can execute zero time if no instance of the class is created and n times if the n instances are created.
RunClassConstructor
runs the static constructor only once, even if you call it twice. Just try ;)
using System.Runtime.CompilerServices;
...
void Main()
{
RuntimeHelpers.RunClassConstructor(typeof(Foo).TypeHandle);
RuntimeHelpers.RunClassConstructor(typeof(Foo).TypeHandle);
Foo.Bar();
}
class Foo
{
static Foo()
{
Console.WriteLine("Foo");
}
public static void Bar()
{
Console.WriteLine("Bar");
}
}
This code prints :
Foo
Bar
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