92

This works fine:

var expectedType = typeof(string);
object value = "...";
if (value.GetType().IsAssignableFrom(expectedType))
{
     ...
}

But how do I check if value is a string array without setting expectedType to typeof(string[])? I want to do something like:

var expectedType = typeof(string);
object value = new[] {"...", "---"};
if (value.GetType().IsArrayOf(expectedType)) // <---
{
     ...
}

Is this possible?

1
  • 1
    Do you want to know if the object was declared as a string[]. or if an object[] contains only instances of a certain type? Commented Mar 11, 2011 at 15:34

7 Answers 7

150

Use Type.IsArray and Type.GetElementType() to check the element type of an array.

Type valueType = value.GetType();
if (valueType.IsArray && expectedType.IsAssignableFrom(valueType.GetElementType())
{
 ...
}

But beware of Type.IsAssignableFrom()! If you want to check for an exact match, you should check for equality (i.e. typeA == typeB). If you want to check if a given type is the type itself or a subclass/interface, then you should use Type.IsAssignableFrom():

typeof(BaseClass).IsAssignableFrom(typeof(ExpectedSubclass))
Sign up to request clarification or add additional context in comments.

Comments

22

You can use extension methods (not that you have to but makes it more readable):

public static class TypeExtensions
{
    public static bool IsArrayOf<T>(this Type type)
    {
         return type == typeof (T[]);
    }
} 

And then use:

Console.WriteLine(new string[0].GetType().IsArrayOf<string>());

Comments

8

The neatest and securest way to do it that found is using MakeArrayType:

var expectedType = typeof(string);
object value = new[] {"...", "---"};
if (value.GetType() == expectedType.MakeArrayType())
{
     ...
}

Comments

7
value.GetType().GetElementType() == typeof(string)

as an added bonus (but I'm not 100% sure. This is the code I use...)

var ienum = value.GetType().GetInterface("IEnumerable`1");

if (ienum != null) {
    var baseTypeForIEnum = ienum.GetGenericArguments()[0]
}

with this you can look for List, IEnumerable... and get the T.

Comments

0

This is another sample,

using System;
using System.Collections.Generic;

public static class Program
{
    public static void Main()
    {
        Type type = typeof(string[]);
        // string[], int[], char[], List<MyData>, IList<MyData>, IEnumarable<MyData>  =====> console write "True",
        // string, int, MyData etc ==== does not write 
        
        if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IList<>))
        {
            Type itemType = type.GetGenericArguments()[0];
            Console.WriteLine("True");
        }

        if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))
        {
            Type itemType = type.GetGenericArguments()[0];
            Console.WriteLine("True");
        }

        if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>))
        {
            Type itemType = type.GetGenericArguments()[0];
            Console.WriteLine("True");
        }
        
        if (type.IsArray)
        {
            Console.WriteLine("True");
        }       
    }
}

public class MyData
{
    public string Name { get; set; }
}

Comments

-3

Do you actually need to know the type of the array? Or do you only need the elements to be of a certain type?

If the latter, you can simply filter only the elements that match what you want:

string[] strings = array.OfType<string>();

Comments

-7
if(objVal.GetType().Name == "Object[]")

true for array

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.