What is a good usage of the is-operator?
The construct below for casting is not the recommended way to go, virtually all documentation prefers the as-operator with a null-check.
if(obj is SomeClass)
{
SomeClass some = (SomeClass)obj;
....
}
And sure this is a (very small) performance increase and some even mention the tread safety.
And yes this is true…
So, why do we have the is-operator?
Where does the “as-operator with a null-check” not work or is not the way to go?
Does is have an advantage to restrict the scope of you declaration you get by using the is-operator?
asdoesn’t work with non-nullablestructs:however:
of course, from 2.0 onwards you could also use:
and test for
nulllike usual.There is also the scenario that you don’t care about the values of the object… you just need to know what it is:
Note that
GetType()is not appropriate for this, as you don’t want to have to consider subclasses, interfaces, etc manually.