Use of "AS" Operator for Type Casting in C#

USAGE of AS operator in C#

Consider the code below.

Problem

Problem with the below mentioned code is that it throws an exception during the casting from the string to int.

object o = "DeveshString";
try
{
  int str = (int) o;
}
catch(Exception ex){...}

This code throws an exception of Invalid Casting.

Solution

We can use the AS operator, it never throws an exception.

int? str = o as int;
if(null != str){...}

If the type cast is unsuccessful then it returns a null value. There is no need of try {}catch{} block


Next Recommended Reading Type Casting In C#