I need to validate an object to see whether it is null, a value type, or IEnumerable<T>
where T
is a value type. So far I have:
if ((obj == null) ||
(obj .GetType().IsValueType))
{
valid = true;
}
else if (obj.GetType().IsSubclassOf(typeof(IEnumerable<>)))
{
// TODO: check whether the generic parameter is a value type.
}
So I've found that the object is null, a value type, or IEnumerable<T>
for some T
; how do I check whether that T
is a value type?
(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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With