Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a dynamic object is an array in c#?

Tags:

c#

.net

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?

like image 382
RollRoll Avatar asked May 29 '12 01:05

RollRoll


People also ask

How do you check if an object is an array in C#?

To do this task, we use the IsArray property of the Type class. This property is used to determine whether the specified type is an array or not. IsArray property will return true if the specified type is an array. Otherwise, it will return false.

How do you declare a dynamic array of objects in C#?

To create arrays dynamically in C#, use the ArrayList collection. It represents an ordered collection of an object that can be indexed individually. It also allows dynamic memory allocation, adding, searching and sorting items in the list.

How do you declare an array of objects in C#?

You declare an array by specifying the type of its elements. If you want the array to store elements of any type, you can specify object as its type. In the unified type system of C#, all types, predefined and user-defined, reference types and value types, inherit directly or indirectly from Object.

Does C# support dynamic arrays?

A dynamic array in C# does not have a predefined fixed size. Here is a code example of dynamic arrays in C#. C# supports both static and dynamic arrays.


2 Answers

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
}

}
like image 34
Dreamer Avatar answered Oct 14 '22 00:10

Dreamer


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); 
like image 86
Tim Schmelter Avatar answered Oct 13 '22 23:10

Tim Schmelter