views:

93

answers:

2

I have a method in a base class

class Base
{
   private static string Colour = "blue";
   string DoStuff() { return ColourProp; }

   protected virtual string ColourProp { get{ return Base.Colour; } }
}

that is called on an instance of this subclass

class Sub
{
   private static string Colour = "orange";

   protected override string ColourProp { get{ return Sub.Colour; } }
}

At the moment I'm using virtual properties, is this the only way? (considering that fields cannot be virtual)...

+1  A: 

Yes, you do need to use either a virtual property or a virtual method to accomplish this. The CLR will dynamically dispatch all calls to ColourProp correctly based on the type of the object (i.e. polymorphism).

Andrew Hare
yeah that's fine, but I was just wondering since ideally (for my problem) the Colour fields belong to the class and not the instance...maybe I can use reflection or something to call the type dynamically???
geejay
They may belong to the class, but you can't do polymorphism on static members, and no, using reflection to do this constitutes a "smell". Maybe you could take a step back and describe what you're trying to achieve at a higher level?
Eric Smith
Ok, I admit it's overkill and smelly to do this. I'm just wondering if there's a way to achieve polymorphism like behaviour with class variables (basically just to cut that extra property out of each subclass, so all I have to do is define a field and then this is used by the superclass).
geejay
A: 

This looks totally fine. Don't worry about virtual properties. This provides not only an encapsulation of your data against other objects but also against subclasses.

h0b0