IS vs AS Operators in C#

CsharpProgrammingServer Side Programming

IS operator

The "is" operator in C# checks whether the run-time type of an object is compatible with a given type or not.

The following is the syntax −

expr is type

Here, expr is the expression

type is the name of the type

The following is an example showing the usage of is operator in C# &minis;

Example

 Live Demo

using System;

class One { }
class Two { }

public class Demo {
   public static void Test(object obj) {
      One x;
      Two y;

      if (obj is One) {
         Console.WriteLine("Class One");
         x = (One)obj;
      } else if (obj is Two) {
         Console.WriteLine("Class Two");
         y = (Two)obj;
      } else {
         Console.WriteLine("None of the classes!");
      }
   }

   public static void Main() {
      One o1 = new One();
      Two t1 = new Two();
      Test(o1);
      Test(t1);
      Test("str");
      Console.ReadKey();
   }
}

Output

Class One
Class Two
None of the classes!

AS Operator

The "as" operator perform conversions between compatible types. It is like a cast operation and it performs only reference conversions, nullable conversions, and boxing conversions. The as operator can't perform other conversions, such as user-defined conversions, which should instead be performed by using cast expressions.

The following is an example showing the usage of as operation in C#. Here as is used for conversion −

string s = obj[i] as string;

Try to run the following code to work with ‘as’ operator in C# −

Example

 Live Demo

using System;

public class Demo {
   public static void Main() {
      object[] obj = new object[2];
      obj[0] = "jack";
      obj[1] = 32;

      for (int i = 0; i < obj.Length; ++i) {
         string s = obj[i] as string;
         Console.Write("{0}: ", i);
         if (s != null)
         Console.WriteLine("'" + s + "'");
         else
         Console.WriteLine("This is not a string!");
      }
      Console.ReadKey();
   }
}

Output

0: 'jack'
1: This is not a string!
raja
Published on 08-Aug-2018 12:51:29
Advertisements