How can I get the ConstructorInfo
for a static constructor?
public class MyClass
{
public static int SomeValue;
static MyClass()
{
SomeValue = 23;
}
}
I've tried the following and failed....
Type myClass = typeof (MyClass);
// throws exception
myClass.TypeInitializer.Invoke(null);
// returns null (also tried deleting BindingFlags.Public
ConstructorInfo ci = myClass.GetConstructor(BindingFlags.Static|BindingFlags.Public, System.Type.DefaultBinder, System.Type.EmptyTypes, null);
// returns empty array
ConstructorInfo[] clutchingAtStraws = myClass.GetConstructors(BindingFlags.Static| BindingFlags.Public);
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.
No, we cannot define a static constructor in Java, If we are trying to define a constructor with the static keyword a compile-time error will occur. In general, static means class level. A constructor will be used to assign initial values for the instance variables.
As MSDN says A static constructor is called automatically to initialize the class before the first instance is created, therefore you can't send it any parameters. We can only pass parameter to a non static constructor(parametrized constructor ) but we can not pass any parameter to a static constructor...
Static class can have static constructor with no access modifier and must be a parameter less constructor,since static constructor will be called automatically when class loads , no point of passing parameters. We can not create constructor of static class, however we can create static constructor for Non static class.
There is also System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(RuntimeTypeHandle type)
, which additionally guarantees that the static constructor is only called once, regardless how many times the method is called:
Type myClass = typeof(MyClass);
System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(myClass.TypeHandle);
Reference
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