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;
}
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.
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.
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.
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);
}
You can do multiple things, depending on the context:
Type.IsAssignableFrom(Type)
if all you've got is two type-instances.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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With