You can check whether there is a generic parameter and whether (the first one) is assignable to IDrivable
.
var firstTypeParameter = inputFoo.GetType().GenericTypeArguments.FirstOrDefault();
if (firstTypeParameter != null && firstTypeParameter.IsAssignableTo(typeof(IDrivable)))
Console.WriteLine("It is a Foo<IDrivable>");
Edit:
As noted in a comment, a more elegant solution can be achieved if you're willing to introduce another interface:
public interface IFoo<out T> { }
public class Foo<T> : Foo, IFoo<T> { }
The check then becomes
if (inputFoo is IFoo<IDrivable> f)
Console.WriteLine("It is a Foo<IDrivable>.");
Regarding the comment:
Of course, using IFoo has the limitation that T can only be used in output positions within that interface.
That is accurate but also not relevant since the purpose of that interface is to make it less cumbersome to interpret metadata about Foo<T>
. To understand that limitation, consider the following:
public interface IFoo<out T>
{
T ThisCompiles();
// void ThisDoesNotCompile(T input);
}
public class Foo<T> : Foo, IFoo<T>
{
public T ThisCompiles() => default;
public T ThisCompilesBecauseNotPartOfIFooInterface(T input)
=> default;
}
The class can use T
as an input or output parameter. Methods on IFoo<T>
could only use T
as an output parameter, but since no methods need be defined on that interface, that restriction is irrelevant.