Reputation: 300
I want to determine some object is derived from IEnumerable
, but Reflection says List<int>
is not a subclass of IEnumerable
.
https://dotnetfiddle.net/an1n62
var a = new List<int>();
// true
Console.WriteLine(a is IEnumerable);
// falsa
Console.WriteLine(a.GetType().IsSubclassOf(typeof(IEnumerable)));
Console.WriteLine(a.GetType().IsSubclassOf(typeof(IEnumerable<>)));
Console.WriteLine(a.GetType().IsSubclassOf(typeof(IEnumerable<int>)));
is
keyword works find, but I have to sovle this without the keyword.
Upvotes: 0
Views: 280
Reputation: 57172
To do what you want, you need to use IsAssignableFrom
:
typeof(IEnumerable).IsAssignableFrom(a.GetType())
The documentation for IsSubclassOf explicitly states this:
The IsSubclassOf method cannot be used to determine whether an interface derives from another interface, or whether a class implements an interface. Use the IsAssignableFrom method for that purpose.
Upvotes: 3