1

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)...

geejay
  • 5,440
  • 8
  • 50
  • 60

2 Answers2

2

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
  • 344,730
  • 71
  • 640
  • 635
  • 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 Aug 04 '09 at 13:18
  • 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 Aug 04 '09 at 13:26
  • 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 Aug 04 '09 at 14:47
0

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
  • 1,802
  • 1
  • 25
  • 44