Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 752
Allrameest Avatar asked Mar 11 '11 15:03

Allrameest


People also ask

How do you check if an object is a certain type of object?

You can check object type in Java by using the instanceof keyword. Determining object type is important if you're processing a collection such as an array that contains more than one type of object. For example, you might have an array with string and integer representations of numbers.

How do you find the type of an object in an array?

In order to get the component type of an Array Object in Java, we use the getComponentType() method. The getComponentType() method returns the Class denoting the component type of an array. If the class is not an array class this method returns null.

How do you check if an object is a string or array C#?

Use IsArray is the method to check the type is array or not along with GetType() method. GetType() method method gets the type of the variable.


2 Answers

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())
{
 ...
}

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

typeof(BaseClass).IsAssignableFrom(typeof(ExpectedSubclass))
like image 145
Stefan Avatar answered Oct 20 '22 15:10

Stefan


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>());
like image 18
Aliostad Avatar answered Oct 20 '22 13:10

Aliostad