The is
keyword is for an object while reflection is needed for a type:
You can use typeof(T).GetInterfaces()
to pull all the interfaces applied to a particular Type.
public void MyMethod(IEnumerable<T> enumerable)
{
var typeInterfaces = typeof(T).GetInterfaces();
if (typeInterfaces.Contains(typeof(IInterface))) {
// Something
}
else if(typeInterfaces.Contains(typeof(IAnotherInterface))) {
// Something Else
}
}
============ Update Based on Comment ============
If T is dynamic you cannot get the information you're looking for from the Type itself since T is could represent any number of different types all at the same time.
You can however loop through each element and test the object itself using the is
keyword.
public static void MyMethod<T>(IEnumerable<T> enumerable)
{
foreach (var dynObj in enumerable)
{
var typeInterfaces = dynObj.GetType().GetInterfaces();
if (typeInterfaces.Contains(typeof(IInterface))) {
// Something
}
else if(typeInterfaces.Contains(typeof(IAnotherInterface))) {
// Something Else
}
}
}
Or if you just want to test all possible interfaces in the enumerable you could do this:
public static void MyMethod<T>(IEnumerable<T> enumerable)
{
var allInterfaces = enumerable.SelectMany(e => e.GetType().GetInterfaces()).ToList();
if (allInterfaces.Contains(typeof(ITheFirstInterface)))
{
Console.WriteLine("Has The First Interface");
}
if (allInterfaces.Contains(typeof(ITheSecondInterface)))
{
Console.WriteLine("Has The Second Interface");
}
}