2

I'm trying to test what kind of array an object is: 1D, 2D, or an array of arrays/jagged array.

Here's what I tried:

    if (o is Array && ((Array)o).Rank == 2) {
        Console.Write ("2D-Array:  ");
    } 
    /* else if (o[0] is Array) {
        Console.WriteLine ("Jagged Array:  ");
    } */
    else if (o is Array) {
        Console.Write ("1D-Array:  ");
    } 

But the middle test doesn't work because Cannot apply indexing with [] to an expression of type 'object'

How else could you do this? Thanks in advance.

1
  • 2
    You can use GetValue. But does this new object[]{new object[0],3} a jagged array? Commented Jan 1, 2015 at 8:02

1 Answer 1

3

Since o is an object and you did not box it as an array, this code won't compile. Here's an easier way:

var arr = o as Array;
if(arr != null) 
{
    if(arr.Rank == 2) 
    {
        Console.Write ("2D-Array:  ");
    } 
    else if (arr.Length > 0 && arr.GetValue(0) is Array) 
    {
        Console.WriteLine ("Jagged Array:  ");
    } 
    else
    {
        Console.Write ("1D-Array:  ");
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

You can not index Array either.
@PetSerAl Correct, I saw Array implements IList but I didn't make sure the implementation wasn't explicit. Fixed.

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.