I'm digging in to custom casts for C# classes. This StackOverflow question gave me a head start, but my class has Type arguments in it. An example is below:
Say I have this class hierarchy for my Entities:
public class Animal
{
}
public class Tiger : Animal
{
public int NumberOfStripes { get; set; }
}
(where Tiger has some properties that Animal does not).
Now, the class I'm trying to perform a custom cast on is similar to the one below (I'm using ASP.NET MVC as a side note)
public class SomeViewModel<T> where T : Animal
{
public T Animal { get; set; }
...
}
When creating the edit forms for this class hierarchy, I need forms specific to an Animal
sub class, but the instantiation of the actual animal
is done using a Type
object. At some point, I need to cast SomeViewModel<Animal>
to SomeViewModel<Tiger>
so I can use a strongly typed Razor view.
An example controller:
namespace MvcProject.Controllers
{
public class AnimalsController : Controller
{
public ActionResult Create(int id)
{
AnimalType t = DbContext.AnimalTypes.Find(id); // get AnimalType object from database
AnimalViewModel<Animal> model = new AnimalViewModel<Animal>()
{
Animal = (Animal)t.CreateInstance() // Returns a Tiger object cast to an Animal
};
return View(model);
}
}
}
In my Razor view, I want to render a partial that is strongly typed to the Tiger
class like so:
@Html.Partial("_TigerForm", Model)
And the contents of the _TigerForm Razor partial:
@model AnimalViewModel<Tiger>
<p>Number of Stripes: @Model.Animal.NumberOfStripes</p>
So couple of questions here:
- Can you do this sort of type cast (from
AnimalViewModel<Animal>
toAnimalViewModel<Tiger>
)? - What other options would be available that would not require type casting? I'd like to avoid a Dynamic view if possible.
Edit #1
Consider the following code:
List<Animal> a = new List<Animal>();
List<Tiger> b = (List<Tiger>)a;
Visual Studio still complains that it cannot cast the object. This seems to be the root of my problem.
Edit #2
This code does work though:
Animal a = new Tiger();
Tiger b = (Tiger)a;