Field belongs to a class, but how to use polymorphism
-
22-07-2019 - |
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)...
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