7

Possible Duplicate:
How do I get the Array Item Type from Array Type in .net

If I have an array of a particular type is there a way to tell what exactly that type is?

 var arr = new []{ "string1", "string2" };
 var t = arr.GetType();
 t.IsArray //Evaluates to true

 //How do I determine it's an array of strings?
 t.ArrayType == typeof(string) //obviously doesn't work
Community
  • 1
  • 1
Micah
  • 111,873
  • 86
  • 233
  • 325

2 Answers2

15

Type.GetElementType - When overridden in a derived class, returns the Type of the object encompassed or referred to by the current array, pointer or reference type.

var arr = new []{ "string1", "string2" };
Type type = array.GetType().GetElementType(); 
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
1

As your type is known at compile time, you can just check in a C++ way. Like this:

using System;

public class Test
{
    public static void Main()
    {
        var a = new[] { "s" }; 
        var b = new[] { 1 }; 
        Console.WriteLine(IsStringArray(a));
        Console.WriteLine(IsStringArray(b));
    }
    static bool IsStringArray<T>(T[] t)
    {
        return typeof(T) == typeof(string);
    }
}

(produces True, False)

Vlad
  • 35,022
  • 6
  • 77
  • 199