Is and As Operator in C#

What are Is and As Operators?

In C#, the is and as operators are used to test and convert types in a safe manner. These operators help check object types at runtime and perform type conversions without throwing exceptions.

Is Operator

The is operator checks if an object is of a certain type and returns true if it is, otherwise false. It is useful for performing type checks before casting objects.

Example: Using the Is Operator

object obj = "Hello, C#";

if (obj is string)
{
    Console.WriteLine("obj is a string");
}
else
{
    Console.WriteLine("obj is not a string");
}
        

In this example, the is operator is used to check if obj is of type string. If true, it prints "obj is a string".

As Operator

The as operator is used to safely cast an object to a specific type. If the object is compatible with the specified type, it returns the object cast to that type. Otherwise, it returns null instead of throwing an exception.

Example: Using the As Operator

object obj = "Hello, C#";

string str = obj as string;
if (str != null)
{
    Console.WriteLine("obj was cast to a string: " + str);
}
else
{
    Console.WriteLine("obj is not a string");
}
        

In this example, the as operator attempts to cast obj to a string. If the cast is successful, it prints the string; otherwise, it returns null.

Difference Between Is and As Operators

While both is and as operators deal with type checking and casting, they have key differences:

Aspect is Operator as Operator
Purpose Checks if an object is of a specified type. Attempts to cast an object to a specified type, returning null if the cast fails.
Result Type Returns a bool (true or false). Returns the object cast to the specified type or null if the cast fails.
Exception Handling Does not perform casting, so no exceptions are thrown. Does not throw exceptions if casting fails; returns null instead.

Key Points to Remember

  • The is operator checks if an object is of a specified type and returns true or false.
  • The as operator attempts to cast an object to a specified type and returns null if the cast is not possible.
  • Use is when you want to check the type of an object without casting it.
  • Use as when you need to perform a safe cast that won't throw an exception if it fails.