Reputation: 163
I have the need to do a few checks like this:
if(thisInstance is ThatClass || thisInstance is ThatOtherClass)
I actually won't be needing to do a lot of these, so I could simply write it as it is above, but I'd still prefer doing this in a more tidy way, eg. like this:
Type[] arrayOfClasses = new Type[] { typeof(ThatClass), typeof(ThatOtherClass))}
if(isOfAnyType(thisInstance, arrayOfClasses))
But for some reason I can't get it to work. For some reason even though the string representations of
thisInstance.GetType()
and
typeof(ThatClass)
would be the same,
thisInstance.GetType().IsInstanceOfType(type)
will still always result in false.
In case it makes a difference, this is a Unity project, so if calling one further GetType() for the comparable items (eg. thisInstance.GetType().GetType()) the result is always System.MonoType, in which case the IsInstanceOfType always returns true, which of course isn't useful either.
Any ideas why the comparison fails or how to make it work? Or should I just give up and simply use the "thisInstance is ThatClass" wherever needed?
Upvotes: 3
Views: 6559
Reputation: 2605
You could use something like this. The method checks a generic object whether it is of any of the types within the array and returns a bool.
public static bool IsOfAnyType<T>(T obj, Type[] types)
{
bool isOfAnyType = false;
for (int i = 0; i < classes.Length; i++)
{
if (types[i].IsAssignableFrom (obj.GetType()))
{
isOfAnyType = true;
break;
}
}
return isOfAnyType;
}
Upvotes: 3
Reputation: 4595
To get your desired way to work you could use this method:
public static bool IsOfAnyType(object obj, Type[] types)
{
return types.Any(type => type.IsInstanceOfType(obj));
}
If you can't use Linq you can write the method like this:
public static bool IsOfAnyType(object obj, Type[] types)
{
foreach (var type in types)
{
if (type.IsInstanceOfType(obj))
return true;
}
return false;
}
To test this I used this code:
Type[] typesToCheck = { typeof(ThatClass), typeof(ThatOtherClass) };
ThatClass input1 = new ThatClass();
ThatOtherClass input2 = new ThatOtherClass();
if (IsOfAnyType(input1, typesToCheck))
Console.WriteLine("Hello world from " + input1.GetType());
if (IsOfAnyType(input2, typesToCheck))
Console.WriteLine("Hello world from " + input2.GetType());
Upvotes: 1
Reputation: 505
You can use isSubclass:
thisInstance.GetType().IsSubclassOf(typeof(ThatClass))
Upvotes: 1