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)?
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.
Yes, you can return an interface.
Pedantically, but crucially, it does not return an interface. It returns an object reference.
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.
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.
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