I know you can't pass in a non IEnumerable based object into an ASP.NET MVC SelectList helper method (as it expects an IEnumerable for the first param). I have a generic list List<OurCustomType> and OurCustomType has properties for things such as value, etc. for the dropdown.

So if I can't pass in a generic object to an IEnumerable, what other options do I have here if I still want to use the SelectList helper?

No correct solution


IEnumerable<T> extends IEnumerable, so List<T> already implements IEnumerable. It should be fine. For example:

List<int> genericList = new List<int>();
IEnumerable<int> genericSequence = genericList;
IEnumerable weakSequence = genericSequence;

If you have a look at the definition of IEnumerable<T> in the framework docs you will see that it inherits off the non-generic IEnumerable. As List<T> inherits IEnumerable<T>, and hence IEnumerable, you'll be able to pass it into your SelectList without problems.

This was done precisely for this issue - backwards compatability with existing non-generic code, although it does make it a tad annoying when implementing your own IEnumerable, as you have to provide the non-generic version as well. Thank the lovely people on the BCL team for that :D

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow