Question

How do I check if an object I receive as a method result is not ValueType and not IEnumerable<ValueType>?

Here is what I wrote:

MethodInfo selectedOverload = SelectOverload(selectedMethodOverloads);
object result = ExecuteAndShowResult(selectedOverload);
ExploreResult(result);

private static void ExploreResult(object result)
{
 if (result != null &&
     !(result is ValueType) &&
     !((IEnumerable)result).GetType().GetProperty("Item").PropertyType) is ValueType)
    )
    Console.WriteLine("explore");
}

Unfortunately type of PropertyType is Type, its content is the type I need to check (e.g. int) but I don't know how to.

EDIT:

Ok, the .IsValueType worked, but now I want also to exclude strings (which are not recognized as ValueTypes), so what?

!(((IEnumerable)result).GetType().GetProperty("Item").PropertyType is string)

doesn't work!

EDIT 2:

Just answered myself:

!(((IEnumerable)result).GetType().GetProperty("Item").PropertyType == typeof(string))

The question remains open about what if I want to check the inheritance from a base class:

!(((IEnumerable)result).GetType().GetProperty("Item").PropertyType == typeof(BaseClass))

doesn't work because typeof checks runtime type, and if PropertyType == InheritedClassType it will return false...

Was it helpful?

Solution

Use Type.IsValueType:

private static void ExploreResult(object result)
{
 if (result != null &&
     !(result.GetType().IsValueType) &&
     !((IEnumerable)result).GetType().GetProperty("Item").PropertyType.IsValueType)
    )
    Console.WriteLine("explore");
}

Although if result is not a value type but not an IEnumerable than you'll get a cast error. That check needs some work.

Answer to second part

!((IEnumerable)result).GetType().GetProperty("Item").PropertyType is string)

is always false because PropertyType returns a Type which is never a string. I think you want

!(result.GetType().GetProperty("Item").PropertyType == typeof(string))

Note that I took out the cast to IEnumerable since you're looking for a property through reflection anyways, so the cast is irrelevant.

Answer to third edit

I want to check the inheritance from a baseclass

For that you want type.IsAssignableFrom():

Type itemType = result.GetType().GetProperty("Item").PropertyType;
bool isInheritedFromBaseClass = 
    typeof(BaseClass).IsAssignableFrom(itemType);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top