Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we have a private constructor in a static class?

Tags:

c#

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

like image 294
Surya sasidhar Avatar asked Jan 27 '10 09:01

Surya sasidhar


3 Answers

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.
like image 117
Ravi Vanapalli Avatar answered Nov 08 '22 19:11

Ravi Vanapalli


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)

like image 23
Winston Smith Avatar answered Nov 08 '22 19:11

Winston Smith


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.

like image 5
Michael Stum Avatar answered Nov 08 '22 21:11

Michael Stum