I have an interface which defines various filtering on data (queries coming from EF4).
Interface method:
IQueryable<T> filter<T>() where T : class;
Now in a concrete implementation of that interface, I want to be able to do:
public IQueryable<T> filter<T>() {
if (...) return query.OfType<Foo>().Take(100);
if (...) return query.OfType<Bar>().Blah();
// etc
}
But of course that doesn’t work as the function signature expects T and not Foo or Bar. Is there some simple way to cast this output, or do I need to forgo the generic approach?
Assuming
FooandBarclasses can both be cast asT, something like this would work:However, you need to make sure that they can both be cast as
T, or else you’ll obviously get InvalidCastExceptions. So you would be well-served to make sureTcan be cast to either type by changing your declaration to someting along the lines of:Where
IFooBaris the base class/interface for bothFooandBar