Difference Between Direct Casting, IS and AS Operator in C#

The below are the available ways in C# when you cast one data type to another.

Direct casting

Direct cast is most common way of casting one type to another, however it yields exception if casting can’t be done.

Below is the example to demonstrate the same.

object length = 3.2;

int test = (int)length; //Fails in runtime

Console.WriteLine(test);

 
is operator

is operator checks whether an object is compatible with a given type (on the right side) and the result of the evaluation is either true (if casting can be done) or false (if casting can’t be done) and since the result is always a Boolean value so there is no chance of runtime exception.

Below is the example to demonstrate the same.

 

object length = 3.2;

if (length is int) //Check if length can be cast to int

{

    Console.WriteLine(length);

} 

as operator

The as operator is like a casting except that it yields null on conversion failure instead of raising an exception. So runtime exception can be avoided using null check.

Below is the example to demonstrate the same.
 

class MyClass //Sample class to test the scenario

{

  int a;

  string b;

}

static void CastMe()

{

   name = new MyClass();

   string test = name as string;

   if (test != null) //Check if test is not null means i.e. casting can be done

   {

     Console.WriteLine(name);

   }

}

Ebook Download
View all
Learn
View all