开发者

Interface Downcasting

开发者 https://www.devze.com 2023-04-10 13:36 出处:网络
Please suppose I have the following extension method in order to be able to force evaluation of an IEnumerable:

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.


An extension method can only be called on an instance. Which means that collection can never be null in your method.

So... as written your method has the exact same behavior the extension method IEnumerable.ToList so I don't see any point.

It would be useful if its return type was IList as Aaron explains in his answer.

Why does IEnumerable.ToList not already return a IList would be a good question for the library designers.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号