The is keyword: Yet another hidden treasure of C#
A while back i blogged about the yield keyword and called it a hidden treasure of C# as I seldom see it used, and many senior developers never use it! Today, I came across a similar one, namely the is-keyword. And frankly, I had actually forgotten about myself, even though I have used it in the past on several occasions.
Say, I want to check if a class is of a certain type, I could do it in the following way:
if (myClass.GetType().Equals(typeof(AnotherClass)))
{
//do something
}
It works fine, but I wouldn't call it "Clean Code", and is not very readable! As a developer it is very easy to end up with this code, because we think: "OK, I have to check if myClass is of a ceratin type, then I need to get its type and compare it to AnotherClass, but to find the type of AnotherClass I have to use the typeof functionality".
Back when I programmed Java I used the instanceof keyword, and this was actually how I rediscovered the is-keyword of C#. The same code segment as above, but using the is-keysword looks far more readable:
if (myClass is MyClass)
{
//do something
}
Even though the expression is not evaluated until run-time, you will get a compile-time warning if the expression is know to always be true or false, eg:
var myClass = new Int32();
if (myClass is Int32)
{
//do something
}
Even though it's a very obvious example, it demonstrates the compile time evaluation! The compiler shows me the following message:
The given expression is always of the provided ('int') type
Strive for clean code, and use is rather than GetType() whenever possible!
July 15th, 2010 - 21:18
Hi,
The is keyword is not equivalent to comparing types using GetType().Equals(typeof(XX)).
Comparing using the is keyword will return true if an instance is compatible with a type, but using Equals(typeof(…) will return true if the types have an exact match.
So in the case of inheritance, using the two compare methods might produce different results.