Shimmy Weitzhandler
Shimmy Weitzhandler

Reputation: 104801

Determine if object is or derives from specific Type?

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

Answers (2)

SoftMemes
SoftMemes

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

Mark Byers
Mark Byers

Reputation: 839044

It sounds like you are looking for IsAssignableFrom:

type.IsAssignableFrom(value.GetType())

Upvotes: 5

Related Questions