I want to create a new instance of a class type only known at runtime, and cast it, based on a given object. I have an "if" statement to make it, since the possible class types are known. However this doesn't seem like a good way to make mantainable or even efficient code. Is there a better way to do this in c# ?
if (car.Color.GetType().ToString() == "My.Domain.ColorBlue")
{
ColorBlue color = new ColorBlue();
}
else if (car.Color.GetType().ToString() == "My.Domain.ColorRed")
{
ColorRed color = new ColorRed();
}
car.Color = color;
return PartialView("XPTO.cshtml", car);
I want to pass the derived class to a MVC View, so I really need it to be casted to the correct type. The view then calls one of many other possible partial views:
if (viewDatatype == "My.Domain.ColorBlue")
{
Html.RenderPartial("XPTOBlue.cshtml", @Model.Color);
}
else if(viewDatatype == "My.Domain.ColorRed")
(...)
and these partial views are strongly typed to one of the derived classes, for example:
@model My.Domain.ColorBlue