C# How to check if an object is a multi-dimensional array

c#, reflection

Solution

There are two main ways to accomplish this. Either by casting `obj` to an `Array` as you suggested:

if(obj is Array && ((Array)obj).Rank == 2)
{
    //do something
}

Or using the `as` operator:

var arr = obj as Array;
if(arr != null && arr.Rank == 2)
{
    //do something
}

Note that in both these solutions, I've combined the two `if`'s together using the conditional AND operator (`&&`) for simplicity. This will only evaluate this right hand side if the left hand side evaluates to `true`.

Problem

I am a newcomer to C#. I have an Object in C#, how to check if it is an single or multi-dimensional array? ``` int[,] array = new int[2,3]; object obj = (object) array; if(obj is Array) { if(obj.Rank==2) // I need to cast obj to array first in order to call Rank { //do something } } ```

Original source