Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why return a collection interface rather than a concrete type? [duplicate]

I've noticed in other people's code that methods returning generic collections will almost always return an interface (e.g. IEnumerable<T> or IList<T>) rather than a concrete implementation.

I have two related questions. Firstly, why (if at all) is it considered better to return an interface? Secondly, is there a collection interface that includes the Sort method (as List<T> does)?

like image 254
David Avatar asked Aug 25 '10 08:08

David


People also ask

What is the return type of interface?

If an interface is defined to be the return type of a method then instances of classes derived from that interface can be returned. The benefit of doing that is no different from returning objects of classes derived from a class.

Can we return an interface in C#?

Yes, you can return an interface.

Can a function return an interface?

Pedantically, but crucially, it does not return an interface. It returns an object reference.


2 Answers

For the first question: if you return an interface, you retain more flexibility. You can change the implementation later to return a different concrete type. On the other hand, it obviously gives the caller less information, so they may not be able to perform certain operations. (e.g. if you return List<T>, the caller can use ConvertAll etc... which they can't if you only declare that you return IList<T>.) In some situations it's worth specifying the concrete type; I generally prefer to at least start with interfaces, and only move to put the concrete type as the return type if I find that I frequently want to use the extra methods available.

Secondly, no standard collection interfaces have a Sort method. On the other hand, you could write an extension method to sort any IList<T>. Personally I usually prefer the LINQ OrderBy, OrderByDescending, ThenBy and ThenByDescending methods... although they return a new sequence, rather than sorting in place.

like image 77
Jon Skeet Avatar answered Oct 14 '22 22:10

Jon Skeet


From C# - List or IList

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 user's 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 may be ok.

like image 30
Michal Ciechan Avatar answered Oct 14 '22 22:10

Michal Ciechan