Possible Duplicate:
C# - List<T> or IList<T>
I have a class
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
}
And I need to define a list and what is the difference between defining it in below ways
IList<Employee> EmpList ;
Or
List<Employee> EmpList ;
IList<>
is an interface. List<>
is a concrete class.
Any of these will be valid:
IList<Employee> EmpList = new List<Employee>();
and
List<Employee> EmpList = new List<Employee>();
or
var EmpList = new List<Employee>(); // EmpList is List<Employee>
However, you cannot instantiate an interface, i.e. the following will fail:
IList<Employee> EmpList = new IList<Employee>();
In general, classes and methods which use dependencies (such as collections) should specify the least restrictive interface possible (i.e. the most general one). e.g. if your method just needs to iterate a collection, then an IEnumerable<>
will suffice:
public void IterateEmployees(IEnumerable<Employee> employees)
{
foreach(var employee in employees)
{
// ...
}
}
Whereas if a consumer needs to access the Count
property (as opposed to having to iterate the collection via Count()
), then a ICollection<T>
or better, IReadOnlyCollection<T>
would be more appropriate, and similarly, IList<T>
would only be required when needing random access to the collection via []
or to express that new items need to be added or removed from the collection.
IList<T>
is an interface implemented by List<T>.
You cannot create a concrete instance of an interface so:
//this will not compile
IList<Employee> EmpList = new IList<Employee>();
//this is what you're really looking for:
List<Employee> EmpList = new List<Employee>();
//but this will also compile:
IList<Employee> EmpList = new List<Employee>();
There are two answers here. For storing the actual list, use an List<T>
because you need a concrete data structure. However, if you return it from a property or require it as an argument, consider a IList<T>
. It is more generic, allowing more types to be passed it for the argument. Similarly, it allows more types to be returned than just the List<T>
in case the internal implementation changes. Indeed, you may want to consider an IEnumerable<T>
for the return type instead.
I'll leave you to enumerate the differences, perhaps with some nifty reflection, but a List<T>
implements several interfaces, and IList<T>
is only one of them:
[SerializableAttribute]
public class List<T> : IList<T>, ICollection<T>,
IList, ICollection, IReadOnlyList<T>, IReadOnlyCollection<T>, IEnumerable<T>,
IEnumerable
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