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

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 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.

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!