I want to do something like the following in C#:
public bool ValidType(Type type)
{
return _someVar is type;
}
C# doesn’t seem to support this syntax though; the item to the right of “is” appears to have to be an absolute type name, not a reference to a type.
I have discovered that the following code seems to work:
return _someVar.GetType().IsInstanceOfType(type) ||
_someVar.GetType().IsSubclassOf(type) ||
_SomeVar.GetType().IsAssignableFrom(type);
I don’t understand what IsAssignableFrom does, other than it seems needed in some type comparisons as IsInstanceOfType and IsSubclassOf don’t seem to match all cases properly.
Is this really the best way to test of a variable is of a type, referred to by another variable, or is there a simpler syntax that I’ve missed?
IsAssignableFromis enough, no need for the other two tests but you are calling it the wrong way round. Here’s the correct way:Actually, it does exactly what the name tells you: it tests whether a variable of a given type is assignable from a value of another type.