9

This MSDN article states that static classes should be declared as sealed and abstract. I was under the impression that static classes were already sealed. Why would you also need to declare a static class as sealed?

Guy
  • 65,082
  • 97
  • 254
  • 325

4 Answers4

27

I think the pertinent bit from that article is:

"Do declare static classes as sealed and abstract, and add a private instance constructor, if your programming language does not have built-in support for static classes."

Remember, the .NET framework supports a lot of different languages.

Dan Diplo
  • 25,076
  • 4
  • 67
  • 89
18

C# v1 did not allow 'static' keyword on class. So if you have a class with only static methods, it was suggested to declare it 'sealed', 'abstract' and make constructor private. This means that no one can instantiate your class or try to inherit from it. [It doesn't make sense to inherit from a class which has only static methods.]

C# v2 allowed the static keyword on a class so you don't have to use the above trick to enforce correct usage.

SolutionYogi
  • 31,807
  • 12
  • 70
  • 78
12
  • One of the effects of marking a class as abstract is that it cannot be instantiated.
  • One of the effects of marking a class as sealed is that is cannot be inherited.

That's what a static class actually is -- a class that cannot be instantiated and that cannot be inherited.

So the article doesn't state you should mark your static classes as abstract and sealed additionally, but this is the way how static classes are represented in IL.

(Other languages may allow you to do this if they do not have a static keyword, although I doubt it, because an abstract sealed class doesn't make a lot of sense semantically.)

dtb
  • 213,145
  • 36
  • 401
  • 431
  • Want to add for future travelers that in 4.0 IL, using static, you get something like '.class private auto ansi sealed'. So yes his answer is the *why*. In C# with static it removes any default constructor that would have been generated for you in IL since in C# it cant be inherited. So static in C# is 'preferred', just complete some of the above answers. – Beeeaaar Jul 15 '13 at 20:46
0

It appears to be saying that declaring a class as sealed and abstract with a private constructor is an alternative to the static class if the language does not support static classes.