Possible Duplicate:
Collection<T> versus List<T> what should you use on your interfaces?
Consider this method—the returned variable myVar is a List<T>, but the return type of the method MyMethod() is an IEnumerable<T>:
public IEnumerable<T> MyMethod(string stuff)
{
var myVar = new List<T>();
//do stuff
return myVar;
}
Essentially, what I want to know is if returning myVar as a different type is OK.
Specifically, with respect to my situation, the ‘do stuff’ goes through a DataRow and assigns the items in that DataRow to a list of objects. I also have similar situations with ICollection and IList return types in other places.
The reason I want to return either IEnumerable or ICollection is so that I’m not returning more than needed. But at the same time, this allows the caller to convert the returned value to a List if it needs to do so.
However, it seems weird that my return statement is returning a List, instead of what the method’s return type is. Is this normal practice? Is there anything wrong with doing this?
Clarification (in response to the dupe comments):
Just to clarify, what I’m curious about is if it is okay that my return statement in the body is returning a List<T>, but the method header has a return-type of IEnumerable, or possibly ICollection, Collection, etc… Something different than than bodies return statement.
Not only there’s nothing wrong with it, but it’s actually good practice: expose only what is strictly necessary. That way, the caller can’t rely on the fact that the method will return a
List<T>, so if for some reason you need to change the implementation to return something else, you won’t break your contract. However the calling code might break if it (incorrectly) made assumptions about what the method actually returns.