In C# how can i check if T is of type IInterface and cast to that if my object supports that interface?

c#, generics, interface

Solution

The missing piece is `Cast<>()`:

if(typeof(IFilterable).IsAssignableFrom(typeof(T))) {
    entities = FilterMe(entities.Cast<IFilterable>()).AsQueryable().Cast<T>();
}

Note the use of `Cast<>()` to convert the entities list to the correct subtype. This cast would fail unless `T` implements `IFilterable`, but since we already checked that, we know that it will.

Problem

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 `interface` and if so call one of the `methods` on that `interface`. I don't want to have `T` constraints to only be of that Type. Is it possible to do this? For example: ``` public class MyModel<T> : IModel<T> where T : MyObjectBase { public IQueryable<T> GetRecords() { var entities = Repository.Query<T>(); if (typeof(IFilterable).IsAssignableFrom(typeof(T))) { //Filterme is a method that takes in IEnumerable<IFilterable> entities = FilterMe(entities)); } return entities; } public IEnumerable<TResult> FilterMe<TResult>(IEnumerable<TResult> linked) where TResult : IFilterable { var dict = GetDict(); return linked.Where(r => dict.ContainsKey(r.Id)); } } ``` The error that I am getting is: Error 21 The type 'TResult' cannot be used as type parameter 'TResult' in the generic type or method 'FilterMe(System.Collections.Generic.IEnumerable)'. There is no implicit reference conversion from 'TResult' to 'IFilterable'.

Original source