Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

c#

.net

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?

like image 503
Yetiish Avatar asked Oct 22 '15 15:10

Yetiish


People also ask

How do you check if an element is an array of arrays?

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 .

How do you check if an object is an array?

The isArray() method returns true if an object is an array, otherwise false .

How do you find the length of an array array?

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.

How do you find if an object is an array in Java?

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.


2 Answers

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.

like image 127
Michael Liu Avatar answered Sep 28 '22 05:09

Michael Liu


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
like image 35
Asad Saeeduddin Avatar answered Sep 28 '22 03:09

Asad Saeeduddin