KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
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.
Tags (comma-separated)
Save Edits
Cancel