Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Comments on When would one not want to return an interface?
Parent
When would one not want to return an interface?
Consider the following method as an example:
List<int> Foo() {
// ...
}
Are there any disadvantages of returning an interface instead of a concrete implementation in C#?
IList<int> Foo() {
// ...
}
From the caller's perspective, it doesn't really matter what the type is as long as it has the correct methods and behaviors (That's the point of interfaces, after all). Taken another way, if I in the future want to change what I return[1], the IList
implementation seems superior in that I don't have to change the return type (as long as my new return value also implements IList
). Why then would I prefer to return by concrete type?
-
Setting aside considerations such as API changes; you can assume this is an internal method not consumed by anyone else. ↩︎
Post
IList<T>
is not necessarily representative of the general case; it's an interface that is (A) widely implemented by a variety of classes from a variety of sources, which themselves (B) tend to add additional functionality or constraints not captured by the signature of IList<T>
. There is, in my opinion, very little if any [see below for one] reason to ever return a List<T>
instead of an IList<T>
, but you could very well want to return a SortedSet<T>
in order to get at its Min
and Max
properties.
Ideally, for that example, there'd be some sort of ISortedSet<T>
interface that would abstract over those properties. But there isn't, as of .NET 7.0, which historically is representative of the story with these abstract collection interfaces. Good ideas, 80% execution. So in practice, sometimes you want to type things concretely.
Peter Taylor adds: ‘Another issue specific to IList<T>
is that for legacy reasons it doesn't inherit from IReadOnlyList<T>
. Returning List<T>
allows callers to assign to IReadOnlyList<T>
, which can make it easier to reason about the calling code.’
For interfaces that don't get around as much, like ye olde IMyInternalApplicationService
, you won't go wrong always favoring those over their concrete implementations everywhere in your code except the place where you tie off your dependency injection knots.
0 comment threads