Brk
Brk

Reputation: 488

Is there a way to pass an argument to the is operator?

I am trying to find an alternative to the following so that I can take advantage of the is operator.

public bool IsOfType(Type type)
{
    return this._item.GetType() == type;
}

Something similar to the following, which does not compile.

public bool IsOfType(Type type)
{
    return this._item is type;
}

Upvotes: 14

Views: 495

Answers (2)

Wim.van.Gool
Wim.van.Gool

Reputation: 1330

You can do multiple things, depending on the context:

  • Use Type.IsAssignableFrom(Type) if all you've got is two type-instances.
  • Use Type.IsInstanceOf(object instance) if you have access to an instance to compare.
  • Use generics like:

    public bool IsOfType<T>()
    {
        return this._item is T;
    }
    

Upvotes: 12

Jon Skeet
Jon Skeet

Reputation: 1499940

I think you're looking for Type.IsAssignableFrom:

public bool IsOfType(Type type)
{
    return _item != null && type.IsAssignableFrom(_item.GetType());
}

Or if you can make the method generic, that's simpler as you can use is with a type parameter:

public bool IsOfType<T>()
{
    return _item is T;
}

EDIT: As noted in Wim's answer, there's also Type.IsInstanceOf which makes the non-generic method simpler:

public bool IsOfType(Type type)
{
    return type.InstanceOf(_item);
}

Upvotes: 28

Related Questions