C# static member "inheritance" - why does this exist at all?

38,265

Solution 1

So, the "inheritance" of static members merely looks like namespace pollution

That's right, except that one guy's pollution is another guy's added spicy flavouring.

I think Martin Fowler, in his work on DSLs, has suggested using inheritance in this way to allow convenient access to static methods, allowing those methods to be used without class name qualification. So the calling code has to be in a class that inherits the class in which the methods are defined. (I think it's a rotten idea.)

In my opinion, static members should not be mixed into a class with a non-static purpose, and the issue you raise here is part of the reason why it's important not to mix them.

Hiding private static mutable data inside the implementation of an otherwise "instancey" class is particularly horrible. But then there are static methods, which are even worse mixers. Here's a typical use of static methods mixed into a class:

public class Thing
{
    // typical per-instance stuff
    int _member1;
    protected virtual void Foo() { ... }
    public void Bar() { ... }

    // factory method
    public static Thing Make()
    {
        return new Thing();
    }
}

It's the static factory method pattern. It's pointless most of the time, but even worse is that now we have this:

public class AnotherThing : Thing { }

This now has a static Make method which returns a Thing, not a AnotherThing.

This kind of mismatch strongly implies that anything with static methods should be sealed. Static members fail to integrate well with inheritance. It makes no sense to have them heritable. So I keep static things in separate static classes, and I gripe about redundantly having to declare every member static when I've already said that the class is static.

But it's just one of those too-late-now things. All real, working languages (and libraries, and products) have a few of them. C# has remarkably few.

Solution 2

I rather have access to all my based static members in derived classes. Otherwise i would need to know exactly where the static member was defined and call it explicitly.

When using Intellisense you can automatically know every static member available to that kind of class.

Of course, they are not inherited, it's just a shortcut

Solution 3

That's how it works, would probably just be a stupid answer in most cases. But in this case, it is how it works; since you derive from A you say that you are A + the extra features you add.

Therefore you need to be able to access the same variables that you would through an instance of A.

However, inheriting a static class makes no sense while access to the static members / fields / methods does.

An example of this is the following:

internal class BaseUser
{
    public static string DefaultUserPool { get; set; }
}
internal class User : BaseUser
{
    public int Id { get; set; }
    public string Name { get; set; }
    public User Parent { get; set; }
}

Where the test looks like this:

User.DefaultUserPool = "Test";
BaseUser.DefaultUserPool = "Second Test";

Console.WriteLine(User.DefaultUserPool);
Console.WriteLine(BaseUser.DefaultUserPool);

Both of the WriteLines outputs "Second Test", this is because both BaseUser and User should use DefaultUserPool, by design. And overriding static implemented methods wouldn't make mucn sense since it's just an accessor in the child-class.

There can be only one. Overriding it would mean that there's a new implementation for that sub-class, which would kill the term "static".

Solution 4

Actually, as I understand it, this is just a shortcut provided by the compiler. Syntax sugar. B.M() will just compile to A.M() since B does not have a static M() and A does. It's for easier writing, nothing else. There is no "static inheritance".

Added: And the requirement for new when "redefining" is just so that you don't accidentally shoot yourself in the foot.

Share:
38,265
Eamon Nerbonne
Author by

Eamon Nerbonne

My work and hobby concern programming: I'm interested in data-mining, and enjoy collecting interesting stats from last.fm's openly accessible web-services. Open source libraries: ValueUtils (nuget: ValueUtils) provides a .NET base class for ValueObjects with auto-implemented GetHashCode and Equals using runtime code generation to perform similar to hand-rolled versions. Can also generate hash function and equality delegates for other types. ExpressionToCode (nuget: ExpressionToCodeLib) generates C# source code from LINQ expression trees and can annotate that code with runtime values, which is hopefully useful in Unit Testing (integrates with NUnit, xUnit.net & mstest, but runs fine without a unit test framework too). a-vs-an (nuget: AvsAn) determines whether "a" or "an" is more appropriate before a word, symbol, or acronym. Fast & accurate. Uses real-world statistics aggregated from wikipedia, and can therefore deal well even with cases that might trip up rules-based systems (e.g. an NSA analyst vs. a NASA flight plan). Includes a C# and Javascript implementation; the javascript implementation you can try online.

Updated on February 20, 2020

Comments

  • Eamon Nerbonne
    Eamon Nerbonne over 4 years

    In C#, a superclass's static members are "inherited" into the subclasses scope. For instance:

    class A { public static int M() { return 1; } }
    class B : A {}
    class C : A { public new static int M() { return 2; } }
    [...]
    A.M(); //returns 1
    B.M(); //returns 1 - this is equivalent to A.M()
    C.M(); //returns 2 - this is not equivalent to A.M()
    

    Now, you can't inherit static classes, and the only place I can imagine that static inheritance might matter ignores it entirely: although you can make a generic constraint that requires a type parameter T to be a subclass of A, you still cannot call T.M() (which probably simplifies things for the VM), let alone write a different M implementation in a subclass and use that.

    So, the "inheritance" of static members merely looks like namespace pollution; even if you explicitly qualify the name (i.e. B.M) A's version is still resolved.

    Edit compare with namespaces:

    namespace N1{  class X();   }
    namespace N1.N2 {  class X();   }
    namespace N1.N2.N3 { [...] }
    

    Within N1.N2.N3 It makes sense that if I use X without qualification it refers to N1.N2.X. But if I explicitly refer to N1.N2.N3.X - and no such class exists - I don't expect it to find N2's version; and indeed to compiler reports an error if you try this. By contrast, if I explicitly refer to B.M(), why doesn't the compiler report an error? After all, there's no "M" method in "B"...

    What purpose does this inheritance have? Can this feature be used constructively somehow?

  • Eamon Nerbonne
    Eamon Nerbonne over 14 years
    The question is why User.DefaultUserPool compiles at all. I far as I can tell, it's merely confusing; it's for instance, as your example points out, not obvious at first sight whether those two distinct static references refer to the same underlying variable. If User had it's own DefaultUserPool (either in another assembly, or with the new keyword) this code would also compile without warning yet result in different output - in short, you can effectively override a static member (even if, for the static case, overriding and hiding is equivalent).
  • Eamon Nerbonne
    Eamon Nerbonne over 14 years
    The "sealed" keyword does that. This doesn't really; an inheriting class can actually replace the base classes implementation - which we'd normally call overriding.
  • Eamon Nerbonne
    Eamon Nerbonne over 14 years
    Put another way, how does being able to say User.DefaultUserPool add anything to being forced to write BaseUser.DefaultUserPool? After all, there is no member or property DefaultUserPool on the class User, it "inherits" this from BaseUser.
  • Filip Ekberg
    Filip Ekberg over 14 years
    In a more abstract manner this makes sense, in a more concrete / implementation manner it might not make as much sense.. But it depends on how you look at it, User Extends BaseUser and therefore you have access to all Public things from BaseUser. There is really no difference in having a non-static and static in this matter, the only difference is that you can Access it by using both BaseUser and User, both of them will reference the same object, since thats what "static" is all about, a chunk of data stored during the entire life cycle of the application..
  • ChrisBD
    ChrisBD over 14 years
    @Eamon - you are quite correct. I had a bit of a brainstorm there.
  • Eamon Nerbonne
    Eamon Nerbonne over 14 years
    If that's the intuition, why can't I access it from generic code? I can guarantee compile-time that all subtypes of A will have some static method M - so why can't I call it? And, this intuition is different from the intuition used for static members of concrete versions of generic types - i.e. if MyType<T> has a static member, this member is different for MyType<int> and MyType<bool> (of course generics aren't exactly subclasses - we're talking design, here). And, worse, what if MyType<T> : A - then MyType<int>.M() does refer to the same method as MyType<bool>.M().
  • Eamon Nerbonne
    Eamon Nerbonne over 14 years
    What I'm trying to get at with my previous comment is not that your idea doesn't make sense - it does - it's just that it's not fully realized (no use for generics, for instance), and I don't see the purpose of doing it that way - the why.
  • Eamon Nerbonne
    Eamon Nerbonne over 14 years
    This isn't questionable behavior - within Subclass, it's clearly consistent for Helper and Base.Helper (and even base.Helper) to resolve to class Base's method Helper. However, it's less clear why Subclass.Helper works.
  • Filip Ekberg
    Filip Ekberg over 14 years
    MyType<int>.M() and MyType<bool>.M() would both refer to the same static method that's because it doesn't matter what the Generic type really is the T only defines the type used Inside the object, not What the objects is. Therefore when MyType<T> derives from A and A has a static member / method, you will always be able to access M() through MyType, dispite what T will ever be.
  • Eamon Nerbonne
    Eamon Nerbonne over 14 years
    That argument holds for non-static members; only wrt instances are types polymorphic in the first place (the wiki summary is misleading). Were static members "polymorphic", then I'd expect (for instance) void CallM<T>() where T:A {T.M();} to work. In any case, you can't actually call/use a static member via a instance anyhow, so not having static inheritance isn't violating polymorphism (i.e. you can't do new A().M();), and there's no general rule that you must be able to use a subtype whereever you could use the base class - parameters are contravariant, for instance.
  • Eamon Nerbonne
    Eamon Nerbonne over 14 years
    But why? You could design a language where if a symbol isn't identified, it picks the symbol in scope that's nearest in name by levenshtein distance, resolving ties lexicographically. It's possible to have aliases which refer to the same entity, but in this case, why do so?
  • Eamon Nerbonne
    Eamon Nerbonne over 14 years
    This makes sense - it's a shorthand helper for intellisense. 'Course, intellisense works best if you only have useful things in scope, so it's not a pure win.
  • Eamon Nerbonne
    Eamon Nerbonne over 14 years
    That's my point - MyType<X>.Q === MyType<Y>.Q sometimes, depending on whether A is defined in MyType<> or in a base type. By contrast, if static members were not inherited this would never be possible.
  • Filip Ekberg
    Filip Ekberg over 14 years
    Don't forget that both MyType<X> and MyType<Y> are still both MyType and if MyType inherits from A and there are static functionallity, they will be "inherited"/"referenceable".
  • Eamon Nerbonne
    Eamon Nerbonne over 14 years
    The alternative would be to allow A.M(); and M(); (just as namespaces would) and to give a compile error on line B.M();
  • Eamon Nerbonne
    Eamon Nerbonne over 14 years
    There are two different issues here - do you allow plain M(); from somewhere within B, and, secondly, what happens when you explicitly say B.M(); I find the argument for the allowing those methods without class name qualification (kind of like extension methods) to be reasonable - but I don't see the point of reinterpreting explicit namespace qualifications, however.
  • Luis Filipe
    Luis Filipe over 14 years
    I'd love see intellisense providing filters, such as, let me see only events, only extensions, etc.. Maybe VS2010 RC1 has it... dind't check it yet
  • Daniel Earwicker
    Daniel Earwicker over 14 years
    I agree on that too, not just because its pointless but may actually be very misleading, especially if the static methods are "factory"-like - see update.
  • Luis Filipe
    Luis Filipe almost 11 years
    I recently learned that R# warns you when referencing a static member from an inherited class
  • Nick Strupat
    Nick Strupat over 10 years
    what about public static T Make<T>() where T : Thing, new() { return new T(); }?
  • Daniel Earwicker
    Daniel Earwicker over 10 years
    @NickStrupat - Why would you use that rather than the new operator directly?
  • Nick Strupat
    Nick Strupat over 10 years
    I'm not sure. I guess if you're using the factory pattern for some reason. I was just thinking within the context of your answer.
  • Asad Saeeduddin
    Asad Saeeduddin almost 10 years
    "One guy's namespace pollution is another guy's added spicy flavoring". I think this might be my new favorite quote of all time.
  • supercat
    supercat almost 9 years
    @EamonNerbonne: It would be helpful if methods could specify if and how they should be seen by inherited classes. If Foo is a widely-used class and it turns out to be necessary to have a type FooBase from which a type Bar descends (without Bar having to descend from Foo) being able to move the static members to FooBase without breaking code that calls them from Foo is useful, but there are times when methods really should only be invokable using the base class.