Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Type to set as return type for methods that return a collection?

Tags:

c#

.net

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?

like image 888
Nate Avatar asked Oct 20 '09 18:10

Nate


People also ask

Which data type can be used as a return type of a method to return any value in C#?

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.

Can a method have 2 return types?

Your answerNo, you don't have two return types.

Which method return type returns a value?

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.

Which method is used in return type of the form list?

reflection - getting type of element in a List in which List is the return type of method in java - Stack Overflow.


1 Answers

The Framework Design Guidelines state:

Use Collection<T> or a subclass of Collection<T> for properties or return values representing read/write collections.

public Collection<Session> Sessions { get; }

Use ReadOnlyCollection<T>, a subclass of ReadOnlyCollection<T>, or in rare cases IEnumerable<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 a GetEnumerator 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.

like image 194
Justin R. Avatar answered Oct 18 '22 08:10

Justin R.