SIGN UP MEMBER LOGIN:    
ARTICLE

The Is and As Operators in C#

Posted by Abhimanyu Kumar Vatsa Articles | C# Language July 05, 2011
In this quick article you will take a look at the "is" and "as" operators in C#.
Reader Level:

Introduction 

Look at the example given below:

Circle c = new Circle(32);

object o = c;

int i = (int)o;        // it compiles okay but throws an exception at runtime

Here the runtime is more suspicious; if the type of object in memory does not match the cast, the runtime will throw an InvalidCastException. We should be prepared to catch this exception and handle it appropriately if it occurs. However, catching an exception and attempting to recover in the event that the type of an object is not what we expected it to be is a rather cumbersome approach. C# provides two more very useful operators that can help us to perform casting in a much more elegant manner by using the "is" and "as" operators. Let's have some discussion of the operators.

is Operator

The "is" operator is used to check whether the run-time type of an object is compatible with a given type or not. In other words, we use the "is" operator to verify that the type of an object is what we expect it to be. Let's look at its syntax: 

expression is type 

Example of the "is" operator:

using System;
class
Class1
{
}

class
Class2
{
}

public
class IsTest
{
   
public static void Test(object o)
   
{
       
Class1 a;
       
Class2 b;
       
if (o is Class1)
       
{
           
Console.WriteLine("o is Class1");
           
a = (Class1)o;
       
}
       
else if (o is Class2)
       
{
           
Console.WriteLine("o is Class2");
           
b = (Class2)o;
       
}
       
else
       
{
           
Console.WriteLine("o is neither Class1 nor Class2.");
       
}
   
}
   
public static void Main()
   
{
       
Class1 c1 = new Class1();
       
Class2 c2 = new Class2();
       
Test(c1);
       
Test(c2);
       
Test("Passing String Value instead of class");
       
Console.ReadKey();
   
}
}

image001.png 

In the above example, I'll be checking whether object o is a class or not. If the argument passed is not a class then the application will jump to the message 'o is neither class1 nor class2'. 

as Operator 

The "as" operator is used to perform conversions between compatible types. Actually, the "as" operator fulfills a similar role like "is" but in a slightly truncated manner. Let's look at its syntax: 

expression as type 

Example of the "is" operator:

using System;
class
Class1
{
}

class
Class2
{
}

public
class IsTest
{
   
public static void Main()
   
{
       
object[] myObjects = new object[6];
       
myObjects[0] = new Class1();
       
myObjects[1] = new Class2();
       
myObjects[2] = "string";
       
myObjects[3] = 32;
       
myObjects[4] = null;
       
for (int i = 0; i < myObjects.Length; ++i)
       
{
           
string s = myObjects[i] as string;
           
Console.Write("{0}:", i);
           
if (s != null)
               
Console.WriteLine("'" + s + "'");
           
else
               
Console.WriteLine("not a string");
       
}
       
Console.ReadKey();
   
}
}
 

image002.png

In the above example, each and every value is being cast to a string using the "as" operator and assigned to a string variable which is shown on the console.

So, that's all about the "is" and "as" operators. Thanks for joining this article.

HAVE A HAPPY CODING!!

Login to add your contents and source code to this article
Article Extensions
Contents added by David Corbin on Jul 10, 2011
Avoiding the "double cast", is something that a beginner should be tought from the very beginning. Although I agree that the details are a little deep, posting as the very first example a "double cast" and then concluding the article with "that is all there is" is very misleading.
share this article :
post comment
 

@David: You are absolutely right. No doubt to say you have good practice over this. But what I mean to say here by this article is simple 'is' and 'as' operator. The thing you have pointed is very deep technical subject that a fresher audience can't understand easily. I hope you understand that. Isn't this?

Posted by Abhimanyu Kumar Vatsa Jul 10, 2011

Performing double casts ("is" followed by "as" or a "hard" cast) is poor practice (possibly neglecting boxed value types). If you are going to potentially use the instance as the target type, then simply use "as" and a null check. Athough slightly oversimplified, consideer the following implementations... "IS" 1) Do alot of work to determine if the cast is valid 2) return true or false. "AS" 1) Do alot of work to determine if the cast is valid 2) return the instance or null "Hard Cast" 1) Do alot of work to determine if the cast is valid 2) return the instance or throw exception When you do "is" followed by one of the other casts, you are performing all of the heavy lifting TWICE. This is unexpected as many other systems, have a very light weight means of determining of an object is of a given type, so for those environment (but not .NET 1.x thru 4.0 at least) it may make sense.

Posted by David Corbin Jul 09, 2011

@Sandeep: Yes, you are right. It provides casting in a much more elegant manner. However, we have lots of another ways and each has its own uses.

Posted by Abhimanyu Kumar Vatsa Jul 05, 2011

Good comparison between IS & AS operators in C#.

Posted by Pradip Pandey Jul 05, 2011

Here in this article as operator is doing type cast one and is operator is doing two times.So AS operator is better comparision IS. Then Why we use IS.(Only for Boolean type value get)

Posted by Sandeep Shekhawat Jul 05, 2011
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites - Click Here!
    Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites - Click Here!
Nevron Gauge for SharePoint
Become a Sponsor