1

Possible Duplicate:
What is the use of static constructors?

From MSDN: - "If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running."

Would you still use Static Constructors for programming construct? Here I'm trying to list down scenarios where and where not one should avail the benefit provided by CLR through the use of Static Constructors.

0

5 Answers 5

4

Would you still use Static Constructors for programming construct?

Sometimes, yes - but only for small things which are staggeringly unlikely to throw exceptions... or where a failure represents a calamitous scenario where the app is fundamentally unusable.

Note that everything you quoted there is true of any static initialization - not just static constructors. So if you have:

private static readonly List<int> SomeValues = new List<int> { 1, 2, 3 };

then that still comes under the same restrictions. Fundamentally, if type initialization fails, your type is unusable. That shouldn't come as any surprise really, and it doesn't mean that it's useless.

0

As the static constructor is invoked only once in the precise moment when type is accessed for the first time, it could become usefull to track down that information during program runtime.

0

It is used to initialize static variables, so if you have them, you should probably use it.

Have a look at this other question maybe it is even duplicated: What is the use of static constructors?

0

Would you still use Static Constructors for programming construct?

Yes. But a static constructor is never supposed to throw an exception, we shouldn't blame the static constructor...

When not use static constructor

An initialization that really costs much, I'd use a lazy property instead.

0

Sometimes you have to use it if you want to init the static members in a little complex way.

Definitely, if you write a complex code, you may get some exceptions, such as file not exist, networking not work. But, you can do it if you really know what you are doing.

So the problem is not whether you should use static constructor, it is due to how you design your software? Why you use static object with complex init needs? If you just want to have a global sole object, you can consider Singleton pattern.

Not the answer you're looking for? Browse other questions tagged or ask your own question.