Search code examples
c#genericsinterfacecasting

Check if generic parameter of a class implements an interface


I have a following generic class:

public class SearchResult<T>
{
    public int ResultCount { get; set; }
    public IEnumerable<T> Result { get; set; }
}

I also have a Bird class, which implements IFlyble interface:

public class Bird : IFlyable
{
    public void Fly() {}
}

public interface IFlyable
{
    void Fly();
}

I also have a variable res of type object. How do I check if res is a SearchResult<IFlyable> ?

I tryied this way:

if (res.GetType().IsAssignableFrom(typeof(SearchResult<IFlyable>)))
{
    ///
}

And this way:

if(res is SearchResult<IFlyable>)
{
    ///
}

But it does not seems to work.


Solution

  • The problem you are having is probably due to the fact that SearchResult<Bird> is not convertible to SearchResult<IFlyable> because SearchResult<T> is invariant in T.

    C# only admits generic type variance in interfaces and delegates. You need to define an ISearchResult<> interface that is covariant in its generic type.

    In your case, if it’s acceptable that T is only used as an output you could define such interface as follows:

    public interface ISearchResult<out T>
    {
         int ResultCount { get; }
         IEnumerable<T> Result { get; }
    }
    

    And now a ISearchResult<Bird> is a ISearchResult<IFlyable> because you’ve given the compiler enough information so that it can verify that the conversion is in fact safe.