Reputation: 703
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?
Upvotes: 10
Views: 5729
Reputation:
An alternative approach that avoids having to interrogate the type in your validation method is to use dynamic dispatch:
// Default overload
public static bool IsValid(object value)
{ return false; }
// If it's an array
public static bool IsValid(Array value)
{
return value.Length > 0;
}
...
bool isValid = IsValid((dynamic)obj); // Will call the overload corresponding to type of obj
Upvotes: 1
Reputation: 55339
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
.
Upvotes: 14