Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I run a static constructor?

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.
like image 845
mafu Avatar asked Apr 16 '10 15:04

mafu


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.

How do you make a constructor static?

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 we apply static to constructor?

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.

How do you make a static constructor in Java?

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


1 Answers

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); 
like image 70
Gary Linscott Avatar answered Sep 23 '22 21:09

Gary Linscott