KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
Context: I sent an email to my colleagues telling them about Enumerable.Empty<T>() as a way to return empty collections without doing something like return new List<T>(); I got a reply saying that the downside is that it doesn't expose a specific type: That does present a tiny issue. It’s always good to be as specific as possible about your return type* (so if you’re returning a List<>, make that your return type); that’s because things like Lists and Arrays have extra methods that are useful. Plus it also can be useful in making performance considerations when using the collection from the calling method. The trick below unfortunately forces you to return an IEnumerable, which is about as non-specific as possible, right? :( * This is actually from the .NET Design Guidelines. Stated reasons in the guidelines are the same as I’m mentioning here, I believe. This seemed to be the complete opposite of what I had learned, and try as I might, I couldn't find this exact advice in the design guidelines. I did find one small piece like this: DO return a subclass of Collection<T> or ReadOnlyConnection<T> from very commonly used methods and properties. With a code snippet following, but no more justification at all. So that being said, is this a real and accepted guideline (the way it was described in the first block quote)? Or has it been misinterpreted? All other SO questions I could find have answers preferring IEnumerable<T> as the return type. Maybe the original .NET guidelines are just outdated? Or maybe it's not so clear cut? Are there some tradeoffs to consider? When would it be a good idea to return a more specific type? Is it ever recommended to return a concrete generic type, or only to return a more specific in
Tags (comma-separated)
Save Edits
Cancel