Explain is and as operators in C# with practical examples.

is and as operators

In C#, the is and as operators are used for type checking and type conversion, respectively. They are particularly useful when working with polymorphism or when the type of an object is not known at compile time.

1. is Operator

The is operator checks if an object is of a specific type and returns a bool (true or false). It does not perform type conversion but simply verifies the compatibility. Example:

object obj = "Hello, world!";
if (obj is string)
{
    Console.WriteLine("The object is a string.");
}

In this example, is checks if obj is of type string.

Use Case: Use is when you want to confirm an object’s type before performing operations on it.

YouTube

2. as Operator

The as operator attempts to convert an object to a specified type. If the conversion succeeds, it returns the object in the new type; otherwise, it returns null. Unlike a cast, it does not throw an exception if the conversion fails. Example:

object obj = "Hello, world!";
string result = obj as string;
if (result != null)
{
    Console.WriteLine($"String value: {result}");
}

Here, as tries to convert obj to a string. If it’s not a string, result would be null.

Use Case: Use as when you want to perform safe type conversion and handle failure gracefully without exceptions.

Key Differences

Featureisas
PurposeChecks type compatibilityConverts to a type safely
Return Typebool (true/false)The converted type or null
FailureNo conversion attemptReturns null, no exception
is and as

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top