David Arno
David Arno

Reputation: 43254

How do I test is a variable is of a variable type in C#?

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?

Upvotes: 2

Views: 136

Answers (2)

Konrad Rudolph
Konrad Rudolph

Reputation: 545588

IsAssignableFrom is enough, no need for the other two tests but you are calling it the wrong way round. Here’s the correct way:

public bool ValidType(Type type)
{
    return type.IsAssignableFrom(_someVar.GetType());
}

I don't understand what IsAssignableFrom does

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.

Upvotes: 4

Rob P.
Rob P.

Reputation: 15071

As Konrad has mentioned IsAssignableFrom is enough for your test.

Determines whether an instance of the current Type can be assigned from an instance of the specified Type.

http://msdn.microsoft.com/en-us/library/system.type.isassignablefrom.aspx

You won't need the other two checks because, in those cases, IsAssignableFrom would also be true.

Upvotes: 1

Related Questions