Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a good usage of the is-operator

Tags:

c#

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?

like image 652
SvenL Avatar asked Nov 29 '12 09:11

SvenL


People also ask

What is the use of IS operator?

The is operator is used to check if the run-time type of an object is compatible with the given type or not. It returns true if the given object is of the same type otherwise, return false. It also returns false for null objects.

What is the use of IS and as in C#?

The is operator returns true if the given object is of the same type, whereas the as operator returns the object when they are compatible with the given type. The is operator returns false if the given object is not of the same type, whereas the as operator returns null if the conversion is not possible.

Is cast C#?

Cast, in the context of C#, is a method by which a value is converted from one data type to another. Cast is an explicit conversion by which the compiler is informed about the conversion and the resulting possibility of data loss.


1 Answers

as doesn't work with non-nullable structs:

object o = 123;
int i = o as int; // compile error

however:

object o = 123;
if(o is int) {
    int i = (int)o;
    //...
}

of course, from 2.0 onwards you could also use:

int? i = o as int?;

and test for null like 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:

if(obj is Something)
    throw new InvalidOperationException("Seriously, don't do that");
// phew! dodged a bullet; we're ok here...

Note that GetType() is not appropriate for this, as you don't want to have to consider subclasses, interfaces, etc manually.

like image 51
Marc Gravell Avatar answered Sep 28 '22 03:09

Marc Gravell