Blog moved to Iserialized.com



Note: My blog has been moved to www.iserialized.com
Please update your link!


Saturday, February 20, 2010

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:

   1:  if (myClass.GetType().Equals(typeof(AnotherClass)))
   2:  {
   3:      //do something
   4:  }

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:

   1:  if (myClass is MyClass)
   2:  {
   3:      //do something
   4:  }

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:

   1:  var myClass = new Int32();
   2:  if (myClass is Int32)
   3:  {
   4:      //do something
   5:  }

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!

0 kommentarer:

Post a Comment

Blog moved to iserialized.com



Note: My blog has been moved to www.iserialized.com
Please update your link!


 
Blogglisten