开发者

Implementation difference in C# [duplicate]

This question already has answers here: List<T> or IList<T> [closed] (18 answers) Closed 8 years ago.

I am a learner of C#.Can you please explain me what is the difference between assigning a collection to interface.

I see some examples,initialize

List<int> few = new List<int>() { 12, 123, 211, 200 }; 

But some a开发者_如何学Gossign collection to interface

IList<int> someList=new List<int>(){12,23,56,78};

When would we need the later one?.Pros and cons with examples will educate me well ,if you kindly provide the one.


Typically you should choose to expose IList rather than List in a public interface, while it would make little difference if the list is used only inside a method:

public IList<int> GetSomeInts()
{
    List<int> result = new List<int>() { 12, 123, 211, 200 };
    return result;
}

This way you decouple the public interface from the concrete type that you actually use internally in your method. You could for instance choose to replace the internal use of List<int> with using a Collection<int> instead without affecting the public interface or users of it, since both implement IList<T>.


When using IList, you will only have access to the methods that are in IList, and not the ones that are in List only (and not in IList).


List is a concrete implementation. this is best suitable if you are the lone consumer. IList provides flexiblity when this is accessed by multiple consumers. So the other consumers wont to change a thing if there is an change in implementation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜