I have a requirement to pass an IEnumerable<Object> to an MVC view and have the view cast this to a strongly typed object and display it accordingly.
This appears to be having a performance impact vs. passing it down as a IEnumerable of MyCustomObject.
foreach (var item in Model.Items)
{
var current = (MyCustomObject) item;
<p>@current.Submitted</p>
}
My questions are
- Should I cast the entire IEnumerable of Objects to IEnumerable of MyCustomObject?
- How can I improve the performance of this operation?
- If this is not good practice, what’s the best way to pass a “variable” type for my Items collection, which could be a collection of any type of custom object?
Initially, you could use Cast on the entire collection:
If your types will all inherit from a base type, say MyCustomObject, then your model should specify this, e.g.
You would need to ensure that any types you wished to add to your items collection inherited from the base
MyCustomObjecttype