Which is the best type to us for returning collections?
Should I use IList<T>
, IEnumerable<T>
, IQueryable<T>
, something else? Which is best and why?
I'm trying to decide which I should use typically, both in the interface and the implementation of a few classes that I'm writing.
edit Let me nail this down a little further, I am using LINQ to SQL to return data over a WCF Service. It feels like that may make a change in the best type to use?
The return type for a Main method may be void or int . The access specifier for the Main method is omitted. In such a case a default one is used, which is private . It is not recommended to use public access specifier for the Main method.
Your answerNo, you don't have two return types.
You declare a method's return type in its method declaration. Within the body of the method, you use the return statement to return the value. Any method declared void doesn't return a value. It does not need to contain a return statement, but it may do so.
reflection - getting type of element in a List in which List is the return type of method in java - Stack Overflow.
The Framework Design Guidelines state:
Use
Collection<T>
or a subclass ofCollection<T>
for properties or return values representing read/write collections.public Collection<Session> Sessions { get; }
Use
ReadOnlyCollection<T>
, a subclass ofReadOnlyCollection<T>
, or in rare casesIEnumerable<T>
for properties or return values representing read-only collections.public ReadOnlyCollection<Session> Sessions { get; }
In general, prefer
ReadOnlyCollection<T>
.
Regarding LINQ, the guidelines, which were created for .NET 3.5, are clear but not (imo) entirely convincing in the justification:
The review body made an explicit decision that LINQ should not change this guideline ["Do not return
IEnumerator<T>
, except as the return type of aGetEnumerator
method"]. Your callers can end up with a clumsy object model if they choose not to use LINQ or a language that does not support it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With