Domanda

Why here interface Ilist is used to create an object of List type

 IList<BankAccountView> bankAccountViews = new List<BankAccountView>();

when it can be done like this

 List<BankAccountView> bankAccountViews = new List<BankAccountView>();
È stato utile?

Soluzione

A List is a concrete type, while an IList is a contract for which you can use any implemtation that an IList has.

An IList has a set of methods as defined on MSDN: http://msdn.microsoft.com/en-us/library/system.collections.ilist.aspx

Here's a very good blogpost explaining it in detail: http://www.claudiobernasconi.ch/2013/07/22/when-to-use-ienumerable-icollection-ilist-and-list/

enter image description here

Altri suggerimenti

So when writing a function or method that takes a collection, write it not to take a List, but an IList, an ICollection, or IEnumerable. The generic interfaces will still work even for heterogenous lists because System.Object can be a T too. Doing this will save you headache if you decide to use a Stack or some other data structure further down the road. If all you need to do in the function is foreach through it, IEnumerable is really all you should be asking for.

On the other hand, when returning an object out of a function, you want to give the user the richest possible set of operations without them having to cast around. So in that case, if it's a List internally, return a copy as a List.

Read link: When to use IList and when to use List

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top