Reputation: 782
How to stop a static constructor(i.e. module constructor & type constructor) from running in .NET?
For example:
class A
{
static A()
{
Environment.Exit(0);
}
static int i()
{
return 100;
}
}
How to invoke i()
without exiting?
Upvotes: 0
Views: 817
Reputation: 19213
As others have mentioned, if you load the type, the static constructor will run. There's no way around it.
You can use Cecil or MS CCI. Both of them allow you to inspect a type without loading it. You can create a dynamic type by cloning class A, and remove the static constructor and finally create the modified type.
Upvotes: 1
Reputation: 273264
Actually i am making a interpreter of .net,
If you use
System.Reflection.Assembly.ReflectionOnlyLoadFrom(fileName);
The static ctor won't run.
Upvotes: 1
Reputation: 1038830
How to stop a static constructor from running in .NET?
You can't do this. Static constructor will be invoked before any instance of the type is created or any static member is referenced. It's called by the CLR and you have absolutely no control over the exact timing.
So the only way to avoid calling the static constructor is to never reference and using the type that contains this static constructor. Why would you define a static constructor in the first place if you don't want it to be executed? Putting an Environment.Exit(0)
instruction into a static constructor is like taking a gun and shooting yourself into the leg.
Upvotes: 5