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?
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.
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.
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.
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))
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>());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With