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:
private static readonly
fields thus cannot be run in a method instead.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.
Java constructor can not be static One of the important property of java constructor is that it can not be static. We know static keyword belongs to a class rather than the object of a class. A constructor is called when an object of a class is created, so no use of the static constructor.
Static constructorsNo, we cannot create a Static constructor in java You can use the access specifiers public, protected & private with constructors. If we try to use static before a constructor a compile time error will be generated saying “modifier static not allowed here”.
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);
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