Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any advantage to declaring a class static in C#? [duplicate]

Tags:

c#

.net

In C#, you can declare a class as static, which requires all members to also be static. Is there any advantage (e.g. performance) to be gained by doing so? Or is it only a matter of making sure you don't accidentally declare instance members in your class?

like image 376
ekolis Avatar asked Dec 13 '25 11:12

ekolis


2 Answers

Or is it only a matter of making sure you don't accidentally declare instance members in your class?

It's that, but it's more than that:

  • It prevents instantiation by not having an instance constructor at all (whereas all other classes have a constructor - either one you declare or an implicit parameterless one)
  • It expresses your intention clearly
  • Nothing can derive from your class (it's both sealed and abstract)
  • Nothing can declare a field of your class type
  • Nothing can use your type as a generic type argument

Basically it tells the compiler and other developers "This is never meant to be instantiated - so if it looks like you're trying to use an instance, you're doing it wrong."

I doubt that there are any performance benefits, but all the above are enough for me :)

Oh, and you can only declare extension methods in static classes too...

like image 78
Jon Skeet Avatar answered Dec 15 '25 00:12

Jon Skeet


I guess you are close to answer, sharing the link which might answer your question. https://softwareengineering.stackexchange.com/questions/103914/why-and-when-should-i-make-a-class-static-what-is-the-purpose-of-static-key

like image 44
Rahul Avatar answered Dec 15 '25 01:12

Rahul