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?
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.
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.
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.
as
doesn't work with non-nullable struct
s:
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.
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