Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I invoke a static constructor with reflection?

Tags:

c#

reflection

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);
like image 819
Dead account Avatar asked Mar 26 '10 16:03

Dead account


People also ask

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.

Can we declare static constructor?

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.

Can static class have parameterized constructor in C#?

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

How do you create a static constructor in a class?

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.


1 Answers

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

like image 166
Oliver Avatar answered Oct 07 '22 18:10

Oliver