Reputation: 771
I understand what static classes and sealed classes are, and I regularly use extension methods, I'm just wondering—does anyone know why static classes are sealed in C#?
I've looked at MSDN and the C# language specification, but it never really says why they're sealed.
Why shouldn't we be able to inherit from static classes and override static members, etc.?
Edit:
I appreciate your answers, but you're still talking about what a static class is. I know why I can't override its methods. But I'm asking why did they make it that way?
Are vtables really that expensive? Why design a langauge so static classes are literally static? Is it just for tradition? Is there another advantage I'm not seeing?
(I have the sneaking suspicion I'm fundamentally misunderstanding the point of static classes.)
Upvotes: 8
Views: 1525
Reputation: 726889
Sealing a class means that you cannot use it as a superclass. Making a class static
makes them useless as base classes, because they cannot have overridable methods. Therefore, deriving from a static class has questionable value: one could argue that you could share protected methods from a static base, but then it is a "one-way street", because derived classes cannot alter functionality of their bases by providing useful overrides.
This boils down the utility of static classes to a namespace-like holder of methods and their associated static data. Letting such classes inherit other static classes would make this purpose less clear while adding very little in terms of functionality or convenience.
Upvotes: 5
Reputation: 203841
You can't inherit static classes because you can't override static members. You can't override static members because the entire concept of overriding members is dependent on virtual dispatch on the type of the implicit parameter, and static members have no implicit parameter to dispatch on.
Upvotes: 10