How to find out if an object's type implements IEnumerable<X> where X derives from Base using Reflec
Posted
by Dave Van den Eynde
on Stack Overflow
See other posts from Stack Overflow
or by Dave Van den Eynde
Published on 2010-03-30T18:02:04Z
Indexed on
2010/03/31
23:13 UTC
Read the original article
Hit count: 461
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 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.
© Stack Overflow or respective owner