Search code examples
c#asp.net-mvcreturn-typeactionmethod

Is it better to return the most specific or most general type from an action method?


What are the benefits or detriments of either?


Solution

  • My guidelines has always been most specific out, and most general in.

    The more general your data type is, the less the code that uses it knows about the data type. For instance, if a method returns a collection, I would return the newly created collection that the method produced. If it returns an internal data structure, I would bump it up to IEnumerable<T>.

    However, if it returns an array, or a List<T> because that's what it built internally, the code that gets hold of your data now has access to more functionality on your collection.

    The other end of the spectrum, to return the most general (within limits) data type would mean that you always return IEnumerable<T> or similar for all collections, even if the method built a new array internally and returned that. The calling code now has to manually copy the contents of the collection into a new array or list, if that is what the calling code needs to use.

    This means more, and in most cases, unnecessary work.

    As for input, I go for the most general type I can use, so for collections, unless I specifically need an array or a list or similar, I will accept IEnumerable<T>. By doing so, I ensure that calling code has less work to do. This might mean that I have to do some work internally, so it's a trade-off.

    The important part is to reach a balance. Don't be too general or too specific, all the time, every time. Figure out the right type that makes sense and consider what the calling code has to do in order to pass data in or accept outgoing data from your code. The less work, the better.