I’m trying to not repeat code, so I have a method that does a quick transform on the property of an interface.
I have 3 concrete classes that make use of this interface, and I want them all to be able to use this method.
The problem comes when I get one of these objects out of Session. I don’t see any way to cast it properly.
public ActionResult GetItems()
{
details = (IHeader<IDetail>)Session["SelectedHeader"].Details // Throws invalid cast
return Json(details);
}
// My interface and class examples:
interface IHeader<T> where T: IDetail
{
IList<T> Details { get; set; }
}
class ConcreteHeader : IHeader<ConcreteDetail>
{
public IList<ConcreteDetail> Items { get; set; }
}
class ConcreteDetail : IDetail
{
...
}
I can’t use generics because this is an action method in ASP.NET MVC 3 (unless there is a trick to that). Is this possible, or do I have to write a method for each class?
EDIT: Not sure if this is clear from original question:
What goes into session is any one of the concrete objects:
Session["SelectedHeader"] = new ConcreteHeader() { Details = new List<ConcreteDetail>() };
If you’re using .NET 4.0, simply cast using the
dynamickeyword to ensure proper automagical type resolution: