Please suppose I have the following extension method in order to be able to force evaluation of an IEnumerable:
public static List<T> EvaluateNow<T>(this IEnumerable<T> collection)
{
if (collection == null)
{
throw new ArgumentNullException("collection");
}
else
{
return (collection.ToList());
}
}
I would like to ask if there is any point in having IList<T> instead of List<T> as this method’s return type (i.e., downcasting to an interface) in order to tie neither it nor its dependencies to a particular implementation (even if the return value will always actually be a List).
It is always a good idea to use interfaces in situations like this rather than classes.
The reasons why are too numerous to get into here, but for example, it greatly increass flexibility as any class just needs to implement the interface
IList<T>to be assignable to the return value of this function. Classes will implement this (or other) interfaces without subclassing List (or equivalent).In general you want to use the ‘lowest’ heirachical interface that fits the requirements. In this case, you could consider ICollection, or even IEnumerable instead of IList.
It is irrelevant what class instance you return from the function, as only ‘the interface’ is returned, so it can be assigned to any class implementing that interface (again, max flexibilty?)
Often a function returning some IEnumerable object will mostly be used inside a foreach loop.