Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List<T> or IList<T> [closed]

Tags:

c#

list

generics

Can anyone explain to me why I would want to use IList over List in C#?

Related question: Why is it considered bad to expose List<T>

like image 491
Peanut Avatar asked Dec 30 '08 12:12

Peanut


People also ask

Why is it IList and not list?

List is used whenever you just want a generic list where you specify object type in it and that's it. IList on the other hand is an Interface.

Is IList faster than list?

Results. IList<T> uses 40 Bytes more than List<T> .

Should I return list or 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.

What is the difference between IList and list?

The main difference between List and IList in C# is that List is a class that represents a list of objects which can be accessed by index while IList is an interface that represents a collection of objects which can be accessed by index.


2 Answers

If you are exposing your class through a library that others will use, you generally want to expose it via interfaces rather than concrete implementations. This will help if you decide to change the implementation of your class later to use a different concrete class. In that case the users of your library won't need to update their code since the interface doesn't change.

If you are just using it internally, you may not care so much, and using List<T> may be ok.

like image 125
tvanfosson Avatar answered Oct 13 '22 10:10

tvanfosson


The less popular answer is programmers like to pretend their software is going to be re-used the world over, when infact the majority of projects will be maintained by a small amount of people and however nice interface-related soundbites are, you're deluding yourself.

Architecture Astronauts. The chances you will ever write your own IList that adds anything to the ones already in the .NET framework are so remote that it's theoretical jelly tots reserved for "best practices".

Software astronauts

Obviously if you are being asked which you use in an interview, you say IList, smile, and both look pleased at yourselves for being so clever. Or for a public facing API, IList. Hopefully you get my point.

like image 30
Arec Barrwin Avatar answered Oct 13 '22 11:10

Arec Barrwin