views:

100

answers:

2

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?

+5  A: 

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.

Darin Dimitrov
I want loading a assembly that have a static constructor that prevent it to be loaded by other programs. Also i see some codes in SSCLI that it controlled by a ClassInit Flag so I believed that there should be some weird way to stop it.
Kii
Assemblies don't have static constructors. Types do.
Darin Dimitrov
there's module constructor and i think that should be static
Kii
@Kii: So you're trying to break into somebody else s code?
Henk Holterman
Actually i am making a interpreter of .net, so i have to control everything in the assembly to prevent clr to execute it. If i can't stop static constructor from running, then it will run twice.
Kii
@Kii: I think you have an architect-designing problem. Not a C# one.
Danny Chen
I think that it is related to .NET CLR so i removed C# tag...And i am loading the assembly using reflection so i can't modify it...
Kii
+1  A: 

Actually i am making a interpreter of .net,

If you use

  System.Reflection.Assembly.ReflectionOnlyLoadFrom(fileName);

The static ctor won't run.

Henk Holterman
Yes, i know the static constructor will not run in reflection only context, but i will not be able to create objects of type in assembly too.
Kii
@Kii, and dotNET's type-safety says you can't create objects w/o running the associated static ctors.
Henk Holterman
yes, so i am going to break type-safety :)
Kii
That means you will have to build your own CLR... good luck.
Henk Holterman