I know that syntactically and conceptually the concepts of “virtual” and “static” members are diametrically opposed, but I’m trying to push the envelope a bit and see if there’s a way to achieve the following:
Let’s say I have an abstract class Animal, which has a property NumberOfLegs. My Cat class should have NumberOfLegs defined as 4, while Spider should have 8 legs. I would want to have code like this (obviously the code below will not compile):
public abstract class Animal {
public static abstract int NumberOfLegs { get; }
public void Walk() {
// do something based on NumberOfLegs
}
}
public class Cat : Animal {
public static override int NumberOfLegs { get { return 4; } }
}
public class Spider : Animal {
public static override int NumberOfLegs { get { return 8; } }
}
I want it to be static, because it’s not dependent on instance; it’s dependent only on the subclass type.
How would you do this?
I think the best compromise for you is to create a constant in each class for the number of legs. A constant is basically a static member which is readonly, which for this example makes sense, otherwise make it static.
Next, I would define an abstract Property for the Animal class and override it each subclass. This would allow inheritance and polymorphism to work, but each instance of the class would still reference the same value.
As far as not being to override static methods, I know it isn’t what you want to hear but that’s not possible. First of all, you use static members like Animal.Legs or Cat.Legs by specifying the class and not from an instance of the object. Therefore, if you define it as static, you won’t even have access on it from an instance of the class, and there is no idea of polymorphism either (i.e. a function accepting a generic “Animal” cannot get how many legs it has and have it call the correct Property). If you are interested in how this works I suggest you read about Virtual Tables