1

I have ViewModelBase with a derived DerivedViewModel

ViewModelBase has DoSomething() which accesses AProperty

DerivedViewModel also uses DoSomething() but it needs to access a different object.

The reason behind this is that the ViewModel is used on a screen, as well as in a Dialog. When it is in a screen, it needs to access a particular entity, but when in a dialog, it needs to access a different entity.

Here it is, simplified, in code. If you run it, they both return A, instead of A, then B. So the question is, how to return A, then B?

class Program
{
    static void Main(string[] args)
    {
        ViewModelBase bc = new ViewModelBase();
        bc.DoSomething(); Prints A

        DerivedViewModel dr = new DerivedViewModel();
        dr.DoSomething(); Prints A, would like it to print B.


    }
}

public class ViewModelBase {

    private string _aProperty = "A";

    public string AProperty {
        get {
            return _aProperty;
        }
    }

    public void DoSomething() {
        Console.WriteLine(AProperty);
    }

}

public class DerivedViewModel : ViewModelBase {

    private string _bProperty = "B";
    public string AProperty {
        get { return _bProperty; }


}
Greg Gum
  • 33,478
  • 39
  • 162
  • 233

1 Answers1

3

Override the property in derived class

public class ViewModelBase 
{
    private string _aProperty = "A";
    public virtual string AProperty 
    {
        get { return _aProperty; }
    }

    public void DoSomething() 
    {
        Console.WriteLine(AProperty);
    }
}

public class DerivedViewModel : ViewModelBase 
{
    private string _bProperty = "B";
    public override string AProperty 
    {
        get { return _bProperty; }
    } 
}

DerivedViewModel dr = new DerivedViewModel();
dr.DoSomething();//Prints B

Further take a look at Msdn Polymorphism

Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
  • This is just what I was looking for. This http://stackoverflow.com/questions/159978/c-sharp-keyword-usage-virtualoverride-vs-new explains why it works (Override vs New) – Greg Gum Aug 18 '13 at 16:26