Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I determine the underlying type of an array [duplicate]

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
like image 732
Micah Avatar asked Jul 05 '12 15:07

Micah


People also ask

How do you find the type of an array?

Array types may be identified by invoking Class. isArray() . To obtain a Class use one of the methods described in Retrieving Class Objects section of this trail.

What is array copy C#?

Copy(Array, Array, Int64) Copies a range of elements from an Array starting at the first element and pastes them into another Array starting at the first element. The length is specified as a 64-bit integer. public: static void Copy(Array ^ sourceArray, Array ^ destinationArray, long length); C# Copy.


2 Answers

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(); 
like image 123
Pranay Rana Avatar answered Sep 20 '22 19:09

Pranay Rana


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)

like image 23
Vlad Avatar answered Sep 23 '22 19:09

Vlad