How to check if an object is an array of a certain type?

This works great:

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

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

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

Is it possible?

+45
arrays reflection c # types
Mar 11 '11 at 15:30
source share
5 answers

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

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

Beware of Type.IsAssignableFrom () . If you want to check the type for an exact match, you must check the equality ( typeA == typeB ). If you want to check if a given type is the type itself or a subclass (or interface), you should use Type.IsAssignableFrom() :

 typeof(BaseClass).IsAssignableFrom(typeof(ExpectedSubclass)) 
+78
Mar 11 2018-11-11T00:
source share
— -

You can use extension methods (not what you need, but to make 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>()); 
+15
Mar 11 '11 at 15:37
source share

The most accurate and safe way to do this using MakeArrayType :

 var expectedType = typeof(string); object value = new[] {"...", "---"}; if (value.GetType() == expectedType.MakeArrayType()) { ... } 
+5
Dec 19 '12 at 16:56
source share
 value.GetType().GetElementType() == typeof(string) 

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

 var ienum = value.GetType().GetInterface("IEnumerable`1"); if (ienum != null) { var baseTypeForIEnum = ienum.GetGenericArguments()[0] } 

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

+3
Mar 11 '11 at 15:38
source share

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

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

 string[] strings = array.OfType<string>(); 
-one
Mar 11 2018-11-11T00:
source share



All Articles