shapper wrote:
On my MVC projects I often create classes which contains properties
which are lists of other classes.
Should I start using IQueryable<Tor IEnumerable<Tin stead of
List<T>?
You probably shouldn't be using List<Tin any case, because it ties you to
one particular implementation. Collection<Tis more extensible, because it
allows you to replace the List<Twith a more specific derived class
allowing you to take action when the collection changes. This isn't possible
if you use List<T>, since it has no hooks for derived classes to alter
behavior. You can always use aggregation, but this is far less convenient.
Better still would be to use IList<Tor ICollection<Tin stead of any
particular class. Programming against interfaces offers the most flexibility
for you as an implementer. Clients miss out on some convenience methods if
you do this, however, and it also won't do if your collection has "special
needs" beyond accessing by index, so this needs to be balanced against use.
You should also make it clear whether your collection is mutable or not, and
enforce this. Offering any of IList<T>, List<Tor Collection<Texp oses
methods to modify the collection. If this is what you want, good (and you'll
probably want to extend Collection<Tto respond to changes), otherwise
there is a ReadOnlyCollect ion<Twrapper that ensures these methods will
fail. Interface-wise it's compatible with IList<T>, ICollection<Tan d
IEnumerable<T>, but not List<T(which is another reason not to use List<T>
in your interface).
What are the differences and when should I use IQueryable<T>,
IEnumerable<Tor List<T>?
IQueryable<T>: probably never. This is only really useful for query
providers. LINQ already contains extension methods for turning any
collection or enumerable into a queryable data source, so there's no point
to offering this specific interface as opposed to IEnumerable<T>. It doesn't
enable clients to do anything more.
IEnumerable<T>: very general and the least useful. The only operation your
clients will be able to perform is foreach, and querying through LINQ. If
this is all you need to offer clients, it'll do. Most LINQ operations will
require enumerating all elements, however, so this is of limited use if
clients will need to be able to use the ordering of elements or the fact
that it's sorted, without forcing them to make array or list copies every time.
List<T>: see above. It's not a good idea to expose it.
--
J.