I have often the case where I want to return an Enumerable<T> from a method or a property. To build the returning Enumerable<T>, I use a List<T>-instance. After filling the list, I return the list.
I always thought that this is enough. But it exists the possibility that the caller casts the resulting Enumerable<T> back into the List<T> and begins to work further with it. If in a later time I change the implementation of my method, the caller’s code will fail. To avoid this, I could return list.ToArray or make a read-only list before returning it to the caller. But for me this seems to be a big overkill. What do you think?
Please note, I never will return an internally used list so that the caller can change my objects internal state. The question is only about a short living list that is built temporary to hold the return values.
IEnumerable<string> GetAList() {
List<string> aList = new List<string>();
aList.Add("a");
aList.Add("b");
return aList;
}
IEnumerable<string> GetAList() {
List<string> aList = new List<string>();
aList.Add("a");
aList.Add("b");
return aList.ToArray<string>();
}
The examples are super-simple and in this case I would work from the beginning on with arrays, but it’s only to show explain the question.
No, this is fine.
This is an example of ‘polymorphism’ at work. Because the caller to the method is only interested in an
IEnumerable<string>, the internal workings of the method are free to return whatever class it likes as long as it derives from theIEnumerable<string>interface.If the caller takes the
IEnumerable<string>and casts up toList<string>then they have broken the contract, which only states that an'IEnumerable<string>will be returned.