Static constructors should be private: a pretty simple rule to follow and one most .NET developers are forced to do. So why do I bring it up? During a webinar earlier today, I demonstrated the new static constructor mocking capabilities in JustMock. I decided to offer that piece of advice because non-private static constructors are a security flaw. However, I was in a C# project, and it’s impossible to use a non-private static constructor anyway.
It’s rare that I need to use static constructors, and I was lacking an example of one with an external dependency. In fact, that’s something I would try to avoid. So, I needed to find a real world example to show why this feature is useful. I did a quick search and found this code analysis entry on MSDN: If a static constructor is not private, it can be called by other code. This is a breaking security issue. I filed this info away and continued my search for a dependency in a static constructor.
I should have read a little further. The article also states: “This rule is enforced by the C# and Visual Basic .NET compilers.” For the vast majority of .NET developers, this rule is irrelevant. Having never had an inclination to make a public static constructor, I failed to realize that I was giving inconsequent advice.
If you’re coding in a language that does support non-private static constructors, please realize the security risk involved. If you are instantiating dependencies in your static constructor, consider a different approach. If one isn’t feasible, JustMock has your back for testing the class.