Let’s write some classes that have static constructors and exceptions get thrown when our static constructor executes.
1
2
3
4
5
6
7
8
9
10
11
12
13
| public class StaticConstructor { public static readonly string varHello = "Hello" ; static StaticConstructor() { throw new Exception( "From static Constructor" ); } public static string SayHello() { return "Hello" ; } } |
Here in this class we’ve got our static constructor. Inside our static constructor, we’re just throwing a new exception to demonstrate.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| [TestClass] public class TestStaticConstructor { [TestMethod] public void CallStaticClassMethod() { try { var variable = StaticConstructor.varHello; } catch (Exception) { //Write Log here } var hello = StaticConstructor.SayHello(); } } |
In our test code here, we’re accessing the varHello field, and this will make our static constructor execute. As I want this demo code to continue, I’ve wrapped this in a try/catch block, and when our static constructor throws the exception, I’m just writing out some log information so we can see what’s going on. So, let’s go ahead and run this.
However, when we write a class that has a static constructor, if that static constructor throws an exception, then our class actually becomes unusable for the remainder of the program. More specifically, our class will remain uninitialized for the remainder of the application domain in which our program is running.
So, when we’re writing classes that have static constructors, we need to be aware that if our static constructor throws an exception, even if that exception is caught in a try/catch block, our class will remain unusable for the remainder of the program’s execution.