18

I have a dynamic object that sometimes is an object and sometimes is an object[].

How can I check if the dynamic object is an array?

3 Answers 3

32

Use Type.IsArray:

From MSDN:

int [] array = {1,2,3,4};
Type t = array.GetType();
// t.IsArray == true
Console.WriteLine("The type is {0}. Is this type an array? {1}", t, t.IsArray); 
Sign up to request clarification or add additional context in comments.

1 Comment

you'r right, I thought it would not work just because it is dynamic(GetType is not shown on intellisense, of course...), but after compile it works fine. thanks
7

Why not just 'is' operator (I just did quick test on immediate windows of Visual Studio debugger), and it works. but not sure if Tim's answer is optimal.

void foo(object o)
{
if( o is System.Array)
{
//its array
}

}

Comments

0

To complement Rango's original response, a more generic way to determine is to use the type's IsSerializable property. Because if the object is a List or any other collection, the IsArray returns false.

int [] array = {1,2,3,4};
Type t1 = array.GetType();
// t1.IsArray == true
List<int> list = new List();
list.AddRange(array);
Type t2 = list.GetType();
//t2.IsArray = false;
//t2.IsSerializable = true;

foreach(var i in list) {
        // do stuff
}

1 Comment

"some text".GetType().IsSerializable is also true but is not an array or list

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.