Question

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

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top