Search code examples
c#static-constructor

How can static constructors be made non-private?


Access modifiers like public, private are not allowed on static constructors in C#. Yet, Visual Studio code analysis has a warning in C# security category that says "CA2121: Static constructors should be private".

Is it possible to make a static constructor non-private? Or is that an error of Visual Studio code analysis?

CLARIFICATION: I'm not trying to make any constructor non-private. So "why?" questions are irrelevant. I'm just curious about the contradiction between two Microsoft tools and want to see if there is anything I don't know about how static constructors are handled.


Solution

  • A C# static constructor is always private. You should never see that warning for C# code, and the warning isn't useful there. Code Analysis is available for other languages too, though, and it's those other languages that may cause you to write classes with non-private static constructors.