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?
Asked
Active
Viewed 332 times
3
-
2Just 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 Answers
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
-
The first point might be a bit misleading. You forgot static constructors :) – Moslem Ben Dhaou Mar 08 '14 at 18:42
-
1@MoslemBenDhaou: Fixed, although in my experience "constructor" with no modifier is pretty much *always* used to implicitly mean "instance constructor". – Jon Skeet Mar 08 '14 at 19:04
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