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.


