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

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?

Jon Skeet
people
quotationmark

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

people

See more on this question at Stackoverflow