Domanda

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.

È stato utile?

Soluzione

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.

Altri suggerimenti

If you read the docs it clearly states

If a static constructor is not private, it can be called by code other than the system. Depending on the operations that are performed in the constructor, this can cause unexpected behavior.

I suppose the more important question would be why would you want to?

Is it possible to make a static constructor not-private?

What would be the sense of it?

A static constructor is called the moment the class is loaded from the linker, before any method executes. As such, a static constructor could not sensible be called outside of the automatic call from the linker, which means there is no sense in it having any access modifier.

Basically you can not reference a class WITHOUT THE STATIC MODIFIER EXECUTING - and that before your code that includes the reference executes.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top