Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

generics

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;
}
like image 778
Brk Avatar asked Jul 24 '13 07:07

Brk


People also ask

Can we pass operator as argument?

I'd pass it as a string, then determine the passed string in the function and e.g use a switch construct to do the corresponding operation. Operators can't be passed like that, and they can't generally be substited by variables, so operators suck that way.

Why do we pass arguments by reference to operators?

Pass-by-references is more efficient than pass-by-value, because it does not copy the arguments. The formal parameter is an alias for the argument. When the called function read or write the formal parameter, it is actually read or write the argument itself.

How do you pass an argument in C++?

The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument. By default, C++ uses call by value to pass arguments.


2 Answers

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);
}
like image 105
Jon Skeet Avatar answered Oct 15 '22 15:10

Jon Skeet


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;
    }
    
like image 44
Wim.van.Gool Avatar answered Oct 15 '22 16:10

Wim.van.Gool