Vadim's Weblog

Never stop learning.

Get Array type.

Posted by Vadim on September 5, 2007

Let assume that you have an int array.

int[] intArr = new int[] { 1, 2 };

If you try to get the type of the array, you’ll get int[] type.

Assert.AreEqual(typeof(int[]), intArr.GetType());

So far so good.  But what if code needs to perform different logic for array of ValueType and Reference Type elements.  We all know that int is a ValueType. However, array of int is not. So the if statement below will output ‘Reference Type’.

if (intArr.GetType().IsValueType)
    Console.Write("ValueType");
else
    Console.Write("Reference Type");

Microsoft provided us with GetElementType method that returns the Type of the object encompassed by the array.

if (intArr.GetType().GetElementType().IsValueType)
    Console.Write("ValueType");
else
    Console.Write("Reference Type");

The code above outputs ‘ValueType’ as expected.

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

%d bloggers like this: