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
For all but the casting part, you can just use:
object newInstance = Activator.CreateInstance(car.Color.GetType());
If that will always implement a particular interface or have a particular base class, you could cast to that - but you can't cast to the actual type, as casting involves knowing the type at compile-time.
So you might have:
Color newColor = (Color) Activator.CreateInstance(car.Color.GetType());
You should always be able to cast to the compile-time type of car.Color
, for starters... For example, if you're just trying to replace the existing Color
property value in car
with a new value of the same type, and if the compile-time type of car.Color
is MyColor
, you can use:
car.Color = (MyColor) Activator.CreateInstance(car.Color.GetType());
See more on this question at Stackoverflow