I have problems with how to do this. I have two classes; ProductViewModel and ProductExtendedViewModel.
My scenario is basically that the ProductExtendedViewModel inherits the ProductViewModel and I want to cast ProductViewModel to ProductExtendedViewModel. How should I go about doing that?
This is what I have tried so far without success:
viewModelExtended = (ViewModelExtended) viewModel;
I get the tip that when casting a number the value must be a number less then infinity
I’m not that great at inherits and casting so this is all kinda new to me so please understand the kinda newbee question.
thanks
EDIT
public class ProductViewModel
{
public string Name { get; set; }
public Product Product { get; set; }
}
public class ProductExtendedViewModel : ProductViewModel
{
public string ExtendedName { get; set; }
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
}
Sadly, in c# you can’t cast from a Base Type to a Derived Type (“downcasting”), because you would be trying to generate information (i.e. what value should ExtendedName have?).
Your best bet would be to do this through composition – create a constructor on
ProductExtendedViewModelthat takes aProductViewModel:Which you could then call:
Note that you can still cast the Derived type back to it’s base type, as this involves a loss of information:
I believe that the “Troubleshooting tip” of “When casting from a number […]” is a red herring in this case, and is just a help around casting in general.