I have Class
B, C, and D inherited from Interface IA
. Now I've got IQueryable<B>
, IQueryable<C>
, and IQueryable<D>
that requires a method to do some stuff with some of the properties in IA
.
public IQueryable<T> DoStuff<T>(IQueryable<IA> samples) where T: IA{
// something that filters samples. Ommited
return samples.Select(s => (T)s).AsQueryable(); // works
//return (IQueryable<T>)samples; //InvalidCastException
}
var samples; // samples can be IQueryable<B>, IQueryable<C>, or IQueryable<D>
samples = DoStuff(samples);
Two questions:
- Why didn't it cast with
IQueryable<T>
? And it did cast when looping and casting one by one. - Initially, B, C, and D inherited from class
A
. That didn't work because I could not cast down a class from A to B, C, D. Then I changedA
toIA
. However, I've read some people said that when you need to cast down an interface to its concrete implementation, you have a design problem. Do I need to avoid casting down here? If so, what's a good approach to achieve the goal?