C# IQueryable – will add different dimension


Just I am maintaining a project.It has been written in C# 3.0.Some Implementations return collection as IQueryable.


List<BookData> data = new List<BookData>();

   data.Add(new BookData { ID = "P001", BookTitle = "C# in Depth" });
   data.Add(new BookData { ID = "P002", BookTitle = "F# in Depth" });

    public IQueryable GetBooks()
        return data.AsQueryable();

The code would have return the collection list. What is the special in returning them
as AsQueryable ?

Best Solution

Without using reflection or casting the returned object, the only methods that are available on the returned collection are those defined by the interface. This would be one way of restricting some types of access to the collection -- for instance, IQueryable doesn't have an add method. Unfortunately this isn't safe in the face of a "hostile" user of your code. If you truly need the collection to be inviolable, a better way is to return a read-only copy of the collection rather than the actual collection cast as a different interface.

Note that I'm assuming a List, as in your example, or some other class that actually implements IQueryable natively. In this case the source object is returned. If the underlying object doesn't implement IQueryable then an IQueryable is returned that proxies the calls to the underlying IEnumerable.