Coding man
Coding man

Reputation: 967

When and why one should make the static constructor as private?

I know the difference between static constructor and private constructor and when to use them. But, when should one make the static constructor as private and what is the advantage of doing this?

Upvotes: 3

Views: 436

Answers (3)

vgru
vgru

Reputation: 51214

Access modifiers are not allowed on static constructors in C#, they are (in a way) always public, meaning that the framework can always access them to perform type-specific initialization. Adding public or private to a static constructor will not compile.

A private constructor is always an instance private constructor, which is a different thing and is most commonly used when creating singletons, to prevent explicit instantiation of the class through user code.

Upvotes: 2

Amogh Natu
Amogh Natu

Reputation: 881

The static constructor should always be private.

Why?

Generally, a static constructor is called by the framework even before the first instance of that class is created. This creates one single instance of that type readily available for usage.

However, if the constructor is not private, it means that other objects can create the instance too. This could possible cause unexpected behaviors.

So, the static constructor should always be private.

Upvotes: 1

Jonathan Allen
Jonathan Allen

Reputation: 70307

The private keyword doesn't actually do anything in C#. By default everything is already private, except non-nested types which are internal because they can't be private.

These days I never use the private keyword, it's just noise.

Note: This is only true for C#. In Visual Basic the default visibility isn't sane and you'll want to explicitly use Private where appropriate.

Upvotes: 0

Related Questions