Possible Duplicate:
C# - List<T> or IList<T>
When I return a list from my method I can do in 2 way. As a List
Private List<datatype> MethodName()
{
Return List
}
As a IList
Private IList<datatype> MethodName()
{
Return IList
}
As I heard we should return it as a IList. Is anyone can explain whys that?
There's a received wisdom that it's always better to return the most specific interface – meaning the interface which has the smallest possible set of functions. By that token, since IEnumerable<T> is smaller than IList<T> you should return IEnumerable<T>.
The IList interface implemented from two interfaces and they are ICollection and IEnumerable. List and IList are used to denote a set of objects. They can store objects of integers, strings, etc. There are methods to insert, remove elements, search and sort elements of a List or IList.
In C# IList interface is an interface that belongs to the collection module where we can access each element by index. Or we can say that it is a collection of objects that are used to access each element individually with the help of an index. It is of both generic and non-generic types.
IEnumerable has just one method called GetEnumerator. This method returns another type which is an interface that interface is IEnumerator. If we want to implement enumerator logic in any collection class, it needs to implement IEnumerable interface (either generic or non-generic).
You can't return an IList
- you need to return an implementation of that interface (i.e. a List
). Of course returning a 'List' will satisfy your method declaration of returning a IList
because List
implements IList
.
Generally best practice is to accept parameters of the most generic type and to return the most specific. However, conventionally programmers tend to not want to tie themselves to the List
implementation and normally return the IList
interface. You could be returning an IEnumerable
if you don't want callers to modify the array (call the .AsReadOnly()
extension method on your IList
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With