Safe Type Cast Using "IS" and "AS" Operators

Introduction

Type casting is one of the important things in software development. In many situations we need to convert one data type to another data type. Sometimes we get an exception like "Cannot implicitly convert type 'XXXX' to 'YYYY'". To avoid this exception, C# provides the two operators "IS" and "AS" to check object compatibility.

IS Operator

The IS operator is useful for checking compatibility with a given type and it returns true if the object is the same type else false.

Example

The following code is useful when an object is a type of my custom class type.

  1. if(obj is Employee)  
  2. {  
  3.    // To DO:  
  4. }  
Characteristic of IS Operator
  • The IS operator cannot be overloaded.

  • It always causes a compile-time warning if the expression is known to be true or to be false, but typically evaluates type compatibility at run time.

    warning

  • An IS operator evaluates to true if the provided expression is non-null and also the provided object can be cast to the provided type without causing an exception to be thrown.

  • The IS operator is only considered to be boxing / unboxing conversions and reference conversions. It is not considered to be another conversion such as user-defined conversions.

  • Anonymous methods are not allowed on the left side of the IS operator.

AS operator

The “AS” operator can be used to perform type conversion between compatible reference types or nullable types. In other words, the AS operator checks whether the type of a given object is compatible with the new object type and it returns a non-null value if the type is compatible with the new one, else null.

Example

  1. Employee emp = obj as Employee;  
Characteristics of AS Operator
  • The AS operator is just like a cast operator. However, it returns null when conversion is not possible instead of raising an exception.
  • The AS operator performs only reference conversions, boxing conversions and nullable conversions. It is not considered to be another conversion such as user-defined conversions.

The “AS” operator uses code to convert that is equivalent to the following expression:

  1. expression is type ? (type)expression : (type)null  
Summary

C# provides the two operators IS and AS for safe type casting.

With the IS operator, we need to do the following to do the cast.
  • Check the type using "IS".
  • If the type is the same then cast.

Employee employee

  1. if(obj is Employee)  
  2. {  
  3.    employee = (Employee)obj;  
  4. }  
The "AS" operator can do the same thing in one step. So only for checking type, we should use the "IS" operator and for type casting use the "AS" operator.

Hope this helps!