i have always thought that returning Arrays were better than lists when having a public API but it seems now there are all these functions on lists that are available through LINQ, etc.
Has the best practice changed here for returning collections of primitives or objects?
for example:
Order[] GetOrders();
List<Order> GetOrders();
IEnumerable<Order> GetOrders();
IQueryable<Order> Get Orders();
For all other return types, Web API uses a media formatter to serialize the return value. Web API writes the serialized value into the response body. The response status code is 200 (OK). A disadvantage of this approach is that you cannot directly return an error code, such as 404.
Leverage action results to return data as an HttpResponseMessage object from your Web API controller method. ASP.Net Web API is a lightweight framework used for building stateless and RESTful HTTP services. You can take advantage of Action Results in Web API to return data from the Web API controller methods.
As I generally only return immutable (unmodifiable) objects from properties/methods, this answer assumes you want to do the same.
Don't forget about ReadOnlyCollection<T>
which returns an immutable collection that can still be accessed by index.
If you're using IEnumerable<T>
and releasing your type into the uncontrollable wilderness, be wary of this:
class MyClass {
private List<int> _list;
public IEnumerable<int> Numbers {
get { return _list; }
}
}
As a user could do this and mess up the internal state of your class:
var list = (List<int>)myClass.Numbers;
list.Add(123);
This would violate the read-only intention for the property. In such cases, your getter should look like this:
public IEnumerable<int> Numbers {
get { return new ReadOnlyCollection<int>(_list); }
}
Alternatively you could call _list.ToReadOnly()
. I wrote it out in full to show the type.
That will stop anyone modifying your state (unless they use reflection, but that's really hard to stop unless you build immutable collections like those use in many functional programming languages, and that's a whole other story).
If you're returning read only collections, you're better off declaring the member as ReadOnlyCollection<T>
as then certain actions perform faster (getting count, accessing items by index, copying to another collection).
Personally I'd like to see the framework include and use an interface like this:
public interface IReadOnlyCollection<T> : IEnumerable<T>
{
T this[int index] { get; }
int Count { get; }
bool Contains(T item);
void CopyTo(T[] array, int arrayIndex);
int IndexOf(T item);
}
You can get all these functions using extension methods on top of IEnumerable<T>
but they're not as performant.
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