Public method returns a lower level interface than the one supported by the value returned.
Warning
When returning a collection from a method, it's often a bad idea to return it type as it may provide capabilities you don't want it to. It's common to want it to be read-only.
The following interfaces give read-only views of a collection:
-
IEnumerable<T>
- allows sequential enumeration and can be used as the source for aforeach
loop. -
IReadOnlyCollection<T>
- same asIEnumerable<T>
plus aCount
property with complexity O(1). -
IReadOnlyList<T>
- same asIReadOnlyCollection<T>
plus an indexer that allows; random access and the use offor
loop, which is often more performant thanforeach
. -
IReadOnlyDictionary<TKey, TValue>
- same asIReadOnlyCollection<KeyValuePair<TKey, TValue>>
plus the read operations found inDictionary<TKey, TValue>
.
It's common to return IEnumerable<T>
but the other interfaces allow the caller to take advantage of the other capabilities.
From the interfaces implemented by the collection you use internally, return the one that provides the most capabilities that are allowed.
Change the return type by the one suggested.
When, for contractual reasons, the return type cannot change.
IEnumerable<int> Method()
{
return new[] { 0, 1, 2, 4, 5 };
}
IReadOnlyList<int> Method()
{
return new[] { 0, 1, 2, 4, 5 };
}