Thursday, September 4, 2008

[.NET] C# 'is' operator

The C# 'is' operator looks like a boring little fella at first, but once you get to know it you will eventually appreciate it - it checks if you can safely cast an instance of an object to a type:
///////////////////////////////////////
//example 1
string testStr = "";
object obj = testStr;

//..somewhere else in your code
string newStr;

if (obj is String)
{
   newStr = (string)obj;
   //go nuts with your string
}
///////////////////////////////////////


It is important to understand that since the 'is' operator is just checking if it is safe to cast the following expression will always be true for any type:
///////////////////////////////////////
//example 2
string var = "whatever";

if(var is object) //<-always true (for var of any type)
{
    //always executed 
}
 /////////////////////////////////////// 
The above is always true for any type because everything in .NET inherits from object. This means you can safely cast to object (box) value types for example, and even if quite obvious it helps understanding how the 'is' operator works. 

You can obtain a result similar to example 1 using GetType and typeof if you're resolving types down to an inheritance line with this code: 
/////////////////////////////////////// 
//example 3 
string testStr = ""; 
object obj = testStr; 

//..somewhere else in your code 
string newStr; 

if (obj.GetType().Equals(typeof(String))) 
   newStr = (string)obj; 
   //have fun with your string 
/////////////////////////////////////// 
But here you're just checking for equality and not for safe casting in general, as you do with operator 'is' (i.e. example 2 with GetType Equals typeof returns false - because GetType returns string does not equal object). For an insight on GetType and typeof see this post.

Closing - a probably more efficient way - depending on your taste - to check if casting is safe is to go ahead and cast using the operator 'as', like this:
///////////////////////////////////////
//example 4
MyClass test =  new MyClass("read between the lines");
object obj = test;

//..somewhere else in your code
MyClass newTest = (obj as MyClass);

if (newStr != null)
{
   //do CRAZY stuff with YourClass
}
///////////////////////////////////////

For more details about the 'as' operator have a look right here.

kick it on DotNetKicks.com

1 comment:

Anonymous said...

Actually, the conditional is false if 'var' is null.

if(var is object) //<-always true