3

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?

ekolis
  • 6,270
  • 12
  • 50
  • 101
  • 2
    Just a small comment/anecdote: That "accidentially declare instance members" was the reason static classes got introduced in C# 2.0. Originally it didn't support it and with .net Framework 1.1 the `Environment` class had an Instance Property, but no public ctor, making that property inaccessible except through reflection which required full trust. – Michael Stum Mar 08 '14 at 09:01

2 Answers2

7

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...

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

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

Community
  • 1
  • 1
Rahul
  • 37
  • 1
  • 8