I need to validate an object to see whether it is null, a value type, or IEnumerable
where T
is a value type. So far I have:
(edit - added value type bits)
You need to check all the interfaces it implements (note it could in theory implement IEnumerable<T>
for multiple T
):
foreach (Type interfaceType in obj.GetType().GetInterfaces())
{
if (interfaceType.IsGenericType
&& interfaceType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
{
Type itemType = interfaceType.GetGenericArguments()[0];
if(!itemType.IsValueType) continue;
Console.WriteLine("IEnumerable-of-" + itemType.FullName);
}
}
My generic contribution that checks if a given type (or its base classes) implements an interface of type T:
public static bool ImplementsInterface(this Type type, Type interfaceType)
{
while (type != null && type != typeof(object))
{
if (type.GetInterfaces().Any(@interface =>
@interface.IsGenericType
&& @interface.GetGenericTypeDefinition() == interfaceType))
{
return true;
}
type = type.BaseType;
}
return false;
}
Can you do somethin with GetGenericArguments
?