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?
Answer: Use the Array. isArray() Method You can use the JavaScript Array. isArray() method to check whether an object (or a variable) is an array or not. This method returns true if the value is an array; otherwise returns false .
The isArray() method returns true if an object is an array, otherwise false .
Using sizeof() function to Find Array Length in C++ Hence, if we simply divide the size of the array by the size acquired by each element of the same, we can get the total number of elements present in the array.
In order to determine if an object is an Object is an array in Java, we use the isArray() and getClass() methods. The getClass() method method returns the runtime class of an object. The getClass() method is a part of the java.
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
.
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
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