Search code examples
c#.netarraysreflectiontypes

How to check if object is an array of a certain type?


This works fine:

var expectedType = typeof(string);
object value = "...";
if (value.GetType().IsAssignableFrom(expectedType))
{
     ...
}

But how do I check if value is a string array without setting expectedType to typeof(string[])? I want to do something like:

var expectedType = typeof(string);
object value = new[] {"...", "---"};
if (value.GetType().IsArrayOf(expectedType)) // <---
{
     ...
}

Is this possible?


Solution

  • Use Type.IsArray and Type.GetElementType() to check the element type of an array.

    Type valueType = value.GetType();
    if (valueType.IsArray && expectedType.IsAssignableFrom(valueType.GetElementType())
    {
     ...
    }
    

    But beware of Type.IsAssignableFrom()! If you want to check for an exact match, you should check for equality (i.e. typeA == typeB). If you want to check if a given type is the type itself or a subclass/interface, then you should use Type.IsAssignableFrom():

    typeof(BaseClass).IsAssignableFrom(typeof(ExpectedSubclass))