C# static member "inheritance" - why does this exist at all?
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.
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, 2020Comments
-
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 ofA
, you still cannot callT.M()
(which probably simplifies things for the VM), let alone write a differentM
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 useX
without qualification it refers toN1.N2.X
. But if I explicitly refer toN1.N2.N3.X
- and no such class exists - I don't expect it to findN2
's version; and indeed to compiler reports an error if you try this. By contrast, if I explicitly refer toB.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 over 14 yearsThe 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 over 14 yearsThe "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 over 14 yearsPut another way, how does being able to say
User.DefaultUserPool
add anything to being forced to writeBaseUser.DefaultUserPool
? After all, there is no member or propertyDefaultUserPool
on the classUser
, it "inherits" this fromBaseUser
. -
Filip Ekberg over 14 yearsIn 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 over 14 years@Eamon - you are quite correct. I had a bit of a brainstorm there.
-
Eamon Nerbonne over 14 yearsIf 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 forMyType<int>
andMyType<bool>
(of course generics aren't exactly subclasses - we're talking design, here). And, worse, what ifMyType<T> : A
- thenMyType<int>.M()
does refer to the same method asMyType<bool>.M()
. -
Eamon Nerbonne over 14 yearsWhat 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 over 14 yearsThis isn't questionable behavior - within Subclass, it's clearly consistent for
Helper
andBase.Helper
(and evenbase.Helper
) to resolve to classBase
's methodHelper
. However, it's less clear whySubclass.Helper
works. -
Filip Ekberg over 14 yearsMyType<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 over 14 yearsThat 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 donew 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 over 14 yearsBut 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 over 14 yearsThis 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 over 14 yearsThat's my point -
MyType<X>.Q === MyType<Y>.Q
sometimes, depending on whether A is defined inMyType<>
or in a base type. By contrast, if static members were not inherited this would never be possible. -
Filip Ekberg over 14 yearsDon'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 over 14 yearsThe alternative would be to allow
A.M();
andM();
(just as namespaces would) and to give a compile error on lineB.M();
-
Eamon Nerbonne over 14 yearsThere are two different issues here - do you allow plain
M();
from somewhere within B, and, secondly, what happens when you explicitly sayB.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 over 14 yearsI'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 over 14 yearsI 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 almost 11 yearsI recently learned that R# warns you when referencing a static member from an inherited class
-
Nick Strupat over 10 yearswhat about
public static T Make<T>() where T : Thing, new() { return new T(); }
? -
Daniel Earwicker over 10 years@NickStrupat - Why would you use that rather than the
new
operator directly? -
Nick Strupat over 10 yearsI'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 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 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 typeFooBase
from which a typeBar
descends (withoutBar
having to descend fromFoo
) being able to move the static members toFooBase
without breaking code that calls them fromFoo
is useful, but there are times when methods really should only be invokable using the base class.