Why can't I inherit static classes?

164,396

Solution 1

Citation from here:

This is actually by design. There seems to be no good reason to inherit a static class. It has public static members that you can always access via the class name itself. The only reasons I have seen for inheriting static stuff have been bad ones, such as saving a couple of characters of typing.

There may be reason to consider mechanisms to bring static members directly into scope (and we will in fact consider this after the Orcas product cycle), but static class inheritance is not the way to go: It is the wrong mechanism to use, and works only for static members that happen to reside in a static class.

(Mads Torgersen, C# Language PM)

Other opinions from channel9

Inheritance in .NET works only on instance base. Static methods are defined on the type level not on the instance level. That is why overriding doesn't work with static methods/properties/events...

Static methods are only held once in memory. There is no virtual table etc. that is created for them.

If you invoke an instance method in .NET, you always give it the current instance. This is hidden by the .NET runtime, but it happens. Each instance method has as first argument a pointer (reference) to the object that the method is run on. This doesn't happen with static methods (as they are defined on type level). How should the compiler decide to select the method to invoke?

(littleguru)

And as a valuable idea, littleguru has a partial "workaround" for this issue: the Singleton pattern.

Solution 2

The main reason that you cannot inherit a static class is that they are abstract and sealed (this also prevents any instance of them from being created).

So this:

static class Foo { }

compiles to this IL:

.class private abstract auto ansi sealed beforefieldinit Foo
  extends [mscorlib]System.Object
 {
 }

Solution 3

Think about it this way: you access static members via type name, like this:

MyStaticType.MyStaticMember();

Were you to inherit from that class, you would have to access it via the new type name:

MyNewType.MyStaticMember();

Thus, the new item bears no relationships to the original when used in code. There would be no way to take advantage of any inheritance relationship for things like polymorphism.

Perhaps you're thinking you just want to extend some of the items in the original class. In that case, there's nothing preventing you from just using a member of the original in an entirely new type.

Perhaps you want to add methods to an existing static type. You can do that already via extension methods.

Perhaps you want to be able to pass a static Type to a function at runtime and call a method on that type, without knowing exactly what the method does. In that case, you can use an Interface.

So, in the end you don't really gain anything from inheriting static classes.

Solution 4

What you want to achieve by using class hierarchy can be achieved merely through namespacing. So languages that support namespapces ( like C#) will have no use of implementing class hierarchy of static classes. Since you can not instantiate any of the classes, all you need is a hierarchical organization of class definitions which you can obtain through the use of namespaces

Solution 5

Hmmm... would it be much different if you just had non-static classes filled with static methods..?

Share:
164,396

Related videos on Youtube

User
Author by

User

Updated on April 12, 2022

Comments

  • User
    User about 2 years

    I have several classes that do not really need any state. From the organizational point of view, I would like to put them into hierarchy.

    But it seems I can't declare inheritance for static classes.

    Something like that:

    public static class Base
    {
    }
    
    public static class Inherited : Base
    {
    }
    

    will not work.

    Why have the designers of the language closed that possibility?

  • User
    User about 15 years
    That's what is left to me. I do it this way. And I don't like it.
  • Lucas
    Lucas about 15 years
    You are saying that static was implemented as abstract + sealed. He wants to know why this was done. Why is it sealed?
  • Anthony D
    Anthony D about 15 years
    As to your first citation, you can cast an instance class as the base class and then use its public members.
  • Thorarin
    Thorarin over 14 years
    Lack of imagination on Torgersen's side, really. I had a pretty good reason for wanting to do this :)
  • Igby Largeman
    Igby Largeman over 14 years
    This doesn't answer the question it all; it just restates the issue he was asking about.
  • Alex Budovski
    Alex Budovski about 14 years
    Well, the OP should have asked "Why are static classes sealed", not "Why can't I inherit from static classes?", the answer to which is of course "because they're sealed". This answer gets my vote.
  • ANeves
    ANeves over 13 years
    I have a generic loader that receives a class as type. That class has 5 helper methods and 2 methods that return a string (name and description). I might have picked it wrong (I think so), but the only solution I found was to instantiate the class in the generic loader, to access the methods... meh.
  • ANeves
    ANeves over 13 years
    The alternative would be a giant dictionary, I guess. Also, when you say "what you want to achieve" you should instead say "what you seem to be aiming for" or something similar.
  • Mark
    Mark almost 13 years
    thanks for sharing that static classes get automatically compiled as sealed classes - I was wondering how/when that happened!
  • user420667
    user420667 over 12 years
    How about this? You have a dll that isn't open source / you don't have access to it's source, let's say NUnit. You want to extend it's Assert class to have a method like Throws<>(Action a) (yes, that's there too, but at one point it wasn't.) You could add to your project a Assert:NUnit.Framework.Assert class, and then add a Throws method. Problem solved. It's cleaner to use in the code too... instead of having to come up with another classname and remember that classname, just type Assert. and see the available methods.
  • user420667
    user420667 over 12 years
    You cannot add methods to an existing static type via an extension method. Please see my comment on the accepted answer for an example desired use. (Basically you would want to just rename what you've named MyNewType as MyStaticType, so MyStaticType: OldProject.MyStaticType)
  • supercat
    supercat over 11 years
    One could define inheritance relations with static types and virtual static members in such a way that a SomeClass<T> where T:Foo could access members of Foo, and if T was a class which overrode some virtual static members of Foo, the generic class would use those overrides. It would probably even be possible to define a convention via which languages could do so in a fashion compatible with the current CLR (e.g. a class with such members should define a protected non-static class which contains such instance members, along with a static field holding an instance of that type).
  • Konrad Morawski
    Konrad Morawski almost 11 years
    @user420667 this could be adressed with extension methods for static classes. No need for inheritance.
  • DeepSpace101
    DeepSpace101 over 10 years
    @AlexBudovski: This answer is correct but as useless as a telling a lost person "you are in front of me" when they ask you "where am I".
  • Martin Braun
    Martin Braun almost 10 years
    @KonradMorawski It's impossible to write extension methods for static classes. stackoverflow.com/questions/249222/…
  • Konrad Morawski
    Konrad Morawski almost 10 years
    @modiX Of course. You misunderstood me here. What I meant is that the functionality required in the scenario described by user420667 could be provided (in future) by as little as allowing extension methods for static classes. No static inheritance necessary. That's why his scenario didn't strike me as a very good rationale for introducing static inheritance. If C# was to be modified in this aspect, why go for a major redesign when a minor one would be just as good in practice.
  • KumarHarsh
    KumarHarsh over 9 years
    @Andrew ,At the same time abstract sealed class cannot be created in c# .So why there is such contradiction .Not able to find good explanation yet .Read this, stackoverflow.com/questions/19404589/…
  • gdbj
    gdbj over 9 years
    I've done it this way as well, but for some reason it doesn't feel aesthetic when you know you will never instantiate the object. I always agonize about details like this, despite the fact that there is no material cost of it.
  • Jasmine
    Jasmine about 9 years
    @boj: Sorry I downvote your answer, because static class can inherit from objects. You didn't mention that. Can you mention that as well as a code as to how to inherit from objects? It shows in visual studio mate.
  • RenniePet
    RenniePet over 6 years
    @Learner That's not really fair. In .Net everything inherits from object, and everyone is expected to know that. So static classes always inherit from object, whether you specify it explicitly or not.
  • Mohammad Nikravesh
    Mohammad Nikravesh over 5 years
    This is the issue, Not the answer
  • Jakub Szułakiewicz
    Jakub Szułakiewicz over 4 years
    In non-static class filled with static methods you cannot put extension methods :)
  • causa prima
    causa prima about 4 years
    I found myself with a case where I believe inheriting a static class is the right thing to do, although obviously you can access them anyway. I have a static class for sending raw data streams to the printer (for talking to industrial label printers). It has a bunch of windows API declarations. I now find myself writing another class for messing with printers which needs the same API calls. Combine? Not good. Declare them twice? Ugly. Inherit? Good, but not permitted.
  • Trikaldarshiii
    Trikaldarshiii over 3 years
    @MohammadNikravesh This is the answer may not be the correct or complete answer but at least an answer
  • Arlen Beiler
    Arlen Beiler over 3 years
    Guys, stating the kind of lock on a door does not answer the question of what the rationale is behind locking the door. The end of the question refers to the designers of the language not the implementers, further reinforcing the idea that he is asking why the decision was made, not how it was implemented. The how is of course informative as well, and fully appropriate if the why question is also answered.
  • boj
    boj almost 3 years
    To the "everything is object" thread: stackoverflow.com/questions/436211/…