10

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?

5
  • Possible duplicate of C# Reflection : how to get an array values & length? Commented Oct 22, 2015 at 15:15
  • Be careful using the term "generic" as it's means something specific in C#, though you can do this in a generic way. Commented Oct 22, 2015 at 15:15
  • You need to make a new array. Value type arrays can't be cast to object[], because all the values need to be boxed. All that aside, what you're doing seems like a code smell; are you sure you can't just accept an Array as the parameter? Commented Oct 22, 2015 at 15:16
  • Are you able to modify the method you are overriding or are you stuck with this method signature? Commented Oct 22, 2015 at 15:18
  • 1
    Not all you code paths return a value. What do you return if value is not an array? Commented Oct 22, 2015 at 15:20

2 Answers 2

14

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Using as you should at least check for array == null.
@MattBurland: Thanks. Fixed.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.