ViewModel Inheritance

129 Views Asked by At

I want to load a screen with a ViewModel depending on the option selected.

I thought Inheritance would be key here, as a lot of the properties are the same. Below is an extract of the code that I have.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        bool isHandheld = false;

        var pdv1 = isHandheld == true ? new PDVHH() : new PDV();

        txtCaseID.Text = pdv1.CaseID;
        txtPDV.Text = isHandheld == true ? pdv1.PDVString : string.Empty;
        txtPDVHH.Text = isHandheld == true ? pdv1.PDVHHString : string.Empty;

    }
}

class basePDV
{
    public string CaseID { get; set; }
}

class PDV : basePDV
{
    public string PDVString { get; set; }
}

class PDVHH : basePDV
{
    public string PDVHHString { get; set; }
}

The error I am receiving is... "Type of conditional expression cannot be determined because there is no implicit conversion between 'WindowsFormsApplication1.PDVHH' and 'WindowsFormsApplication1.PDV'"

I'm hoping someone can give me some guidance on a solution for this.

2

There are 2 best solutions below

7
On

Ok, your question is not really about inheritance or ViewModels but about how ?: (the conditional operator) works.

The following will fix it:

var pdv1 = isHandheld == true ? (basePDV) new PDVHH() : (basePDV) new PDV();

While your code looks plausible, the docs say that you need a conversion between PDVHH and PDV, either direction, but the conversion to basePDV isn't considered.

When you can find a common name for PDVString and PDVHHString and implement it as a single property in the base class, it might work like you want. And even simpler. Note that class PDV : basePDV {} is Ok.

4
On

The C# language specification distinguishes between three types of statements. In general you can have these statements:

labeled-statement - This is for a go-to statement

declaration-statement - This is for a variable declaration

embedded-statement - Which applies to all the remaining statements

In the if statement the body has to be embedded-statement, which explains why the first version of the code doesn't work.

if ( boolean-expression ) embedded-statement if ( boolean-expression ) embedded-statement else embedded-statement

A variable declaration is declaration-statement, so it cannot appear in the body. If you enclose the declaration in brackets, you'll get a statement block, which is an embedded-statement (and so it can appear in that position).

var pdv1 = isHandheld == true ? new PDVHH() : new PDV(); is considered a declaration-statement.

//var pdv1 = isHandheld == true ? new PDVHH() : new PDV(); won't work but the following will

// The above is the equivalent of the below statement which will NOT work.
if (isHandheld)
      var pdv1 = new PDVHH();
else
      var pdv1 = new PDV();

if (isHandheld)
{
    var pdv1 = new PDVHH();
}
else
{
    var pdv1 = new PDV();
}