Reputation: 196479
I have a collection IQueryable<Car>
and I want to pass it into a generic function that takes in as a parameter IQueryable<T>
, something like (which is sitting in a base class).
public abstract class BaseController<T> : ControllerBase where T : BaseObj, new()
{
public IQueryable<T> FilterEntities(IQueryable<T> entities)
{
}
}
What is the right way to pass this in? Cast? Safety cast?
Upvotes: 0
Views: 534
Reputation: 7584
public IQueryable<TQueryable> FilterEntities<TQueryable>(
IQueryable<TQueryable> entities)
{
}
You need to make the method a generic method (the <T> after the function name before the parens tells the compiler the method is generic).
The type parameter TQueryable
of the method differs from the class type. If you don't want it to your method signature should be fine.
Upvotes: 1
Reputation: 21742
your problem is that your method isn't generic, the class is. Notice there' no <T>
after then method name, than mean you have to pass in an IQueryable of what ever was yoused for the type argument for the class.
E.g if the object was instantiated like this:
new BaseController<BaseObject>(..) //ignoring that BaseController is abstract
you'd need to pass an IQueryable<BaseObject>
so in your case where you wish to pass in an IQueryable<Car>
the type of controller needs to derive from BaseController<Car>
If on the other hand you wish the method to be generic change the signature of the method to
public IQueryable<TElement> FilterEntities<TElement>
(IQueryable<TElement> entities)
that does not include the type contraint on T you have on the type parameter for the class. If this is should be enforced for the generic method the signature needs to be:
public IQueryable<TElement> FilterEntities<TElement>(IQueryable<TElement> entities)
where TElement : BaseObj, new()
EDIT If you wish to have a "default" method that simply uses T as the type argument you will have to implement it as a non generic method just as you have in your code so the class would be:
public abstract class BaseController<T> : ControllerBase
where T : BaseObj, new()
{
public IQueryable<T> FilterEntities(IQueryable<T> entities)
{
return FilterEntities<T>(entities);
}
public IQueryable<TElement> FilterEntities<TElement>(IQueryable<TElement> entities)
where TElement : BaseObj, new()
}
Upvotes: 2
Reputation: 6322
Define the FilterEntities as below
public IQueryable<T> FilterEntities<T>(IQueryable<T> entities)
{
}
Now you can pass IQueryable as below
IQueryable<Car> x = null; //Initialize it
FilterEntities<Car>(x);
Upvotes: 0