Surya sasidhar
Surya sasidhar

Reputation: 30343

Can we have a private constructor in a static class?

I have a doubt that a static class can contain a private constructor.

Upvotes: 8

Views: 12561

Answers (5)

Ravi Vanapalli
Ravi Vanapalli

Reputation: 9950

Static classes cannot have instance constructors

http://msdn.microsoft.com/en-us/library/79b3xss3.aspx

The following list provides the main features of a static class:

  • Contains only static members.
  • Cannot be instantiated.
  • Is sealed.
  • Cannot contain Instance Constructors.

Upvotes: 8

Winston Smith
Winston Smith

Reputation: 21932

A static class cannot have any instance constructor ( see CS0710 ), whether it be public, private, protected or internal.

See the following article for more info.

Static Classes and Static Class Members (C# Programming Guide)

Upvotes: 6

RameshVel
RameshVel

Reputation: 65887

rule is static classes cannot have instance constructors

Upvotes: 3

Henk Holterman
Henk Holterman

Reputation: 273844

Your doubt is correct.

A static class can only have a static constructor and public/private does not apply since your code can never call this constructor (the CLR does).

So you may not use a access modifier (public/private/...) on a static constructor.

Upvotes: 4

Michael Stum
Michael Stum

Reputation: 181104

What would this constructor do? The class is static, so it is never instantiated. You can have a static constructor on a non-static class to initialize static fields, but on a static class, the only constructor that makes sense is the static constructor, and that gets called be the CLR.

Addition: Jon Skeet posted an article about the timing of the initialization of the static class (normally it's initialized on first use, but sometimes you want to initialize it when the program starts) and a possible change in .net 4.

Upvotes: 5

Related Questions