Reputation: 104801
I'm looking for the is
operator, except that the type operand (right) is dynamic.
public static bool Is(this object value, Type type)
{
if (type == null) throw new ArgumentNullException(type, "type");
if (value == null) return false;
var valueType = value.GetType();
return valueType == type || valueType.IsSubclassOf(type)
|| valueType implements interface
}
Is there a simpler way of doing it?
I tried using IsAssignableFrom
, but it doesn't seem to be working:
var x = "asdf";
Console.WriteLine(x.GetType().IsAssignableFrom(typeof(object)));
Console.WriteLine(x is object);
Upvotes: 2
Views: 315
Reputation: 5712
Yes, there is a better way, you just have to reverse your problem. Instead of asking if valueType is a subclass of type, check if type is assignable from valueType. Luckily, there is a call to do exactly that, see IsAssignableFrom
Upvotes: 3
Reputation: 839044
It sounds like you are looking for IsAssignableFrom
:
type.IsAssignableFrom(value.GetType())
Upvotes: 5