Give a base class Base
, I want to write a method Test, like this:
private static bool Test(IEnumerable enumerable)
{
...
}
such that Test returns true if the type of o implements any interface of IEnumerable<X>
where X
derives from Base
, so that if I would do this:
public static IEnumerable<string> Convert(IEnumerable enumerable)
{
if (Test(enumerable))
{
return enumerable.Cast<Base>().Select(b => b.SomePropertyThatIsString);
}
return enumerable.Cast<object>().Select(o => o.ToString());
}
...that it would do the right thing, using Reflection. I'm sure that its a matter of walking across all the interfaces of the type to find the first that matches the requirements, but I'm having a hard time finding the generic IEnumerable<>
among them.
Of course, I could consider this:
public static IEnumerable<string> Convert(IEnumerable enumerable)
{
return enumerable.Cast<object>().Select(o => o is Base ? ((Base)o).SomePropertyThatIsString : o.ToString());
}
...but think of it as a thought experiment.