Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why its better (Return IList Instead of return List)? [duplicate]

Tags:

c#

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?

like image 837
Charitha Avatar asked Feb 07 '11 10:02

Charitha


People also ask

Is it better to return IEnumerable or list?

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>.

When should use IList or list?

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.

What is IList in C# with example?

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.

What is the return type of IEnumerable?

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).


1 Answers

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).

like image 193
David Neale Avatar answered Oct 05 '22 20:10

David Neale