In C#, I have a function that passes in T
using generics
and I want to run a check to see if T
is an object
that implements a
In my answer, I assume that method FilterMe
is used internally and should not be visible outside your model and could be marked private
. If my assumption is wrong, you could create a private overload of FilterMe
.
In my answer I just removed the generic
. I assume that this FilterMe
always is about then entities of type T
(since it is in the same Model class). This solves the problem about casting between T
and TResult
. TResult
does not have to be marked as IFilterable
since none of the members of IFilterable
are used. And since the code already checks if T
is IFilterable
why check again (especially when FilterMe
would be private)?
public IQueryable GetRecords()
{
var entities = Repository.Query();
if (typeof(IFilterable).IsAssignableFrom(typeof(T)))
{
//Filterme is a method that takes in IEnumerable
entities = FilterMe(entities).AsQueryable();
}
return entities;
}
public IEnumerable FilterMe(IEnumerable linked)
{
var dict = GetDict();
return linked.Where(r => dict.ContainsKey(r.Id));
}
If you would create a second FilterMe
, replace the IEumerable
types with Queryable
, so you do not have to convert your entities with AsQueryable()
.