Q:

Determine if an object is an array of any type, and access the array length

I have an overridden method that has an object parameter. I am determining if this is an array, and then want to determine its length:
public override bool IsValid(object value)
{
    Type type = value.GetType();
    if (type.IsArray)
    {
        return ((object[]) value).Length > 0;
    }
    else
    {
        return false;
    }
}

The problem is if value is an int[], it errors when I try to cast to an object[]. Is there any way to handle this cast so it will work with any type of array?

A:

Cast value to the base System.Array class:
return ((Array) value).Length > 0

By using the as operator, you can simplify your code further:
public static bool IsValid(object value)
{
    Array array = value as Array;
    return array != null && array.Length > 0;
}

Note: This will return true for multidimensional arrays such as new int[10, 10]. If you want to return false in this case, add a check for array.Rank == 1.

