0
0
C Sharp (C#)programming~5 mins

Casting with as and is operators in C Sharp (C#)

Choose your learning style9 modes available
Introduction

We use as and is to safely convert one type to another without errors. This helps check or change types in a friendly way.

When you want to check if an object is a certain type before using it.
When you want to convert an object to another type but avoid exceptions if it fails.
When working with different types in a collection and need to handle them differently.
When you want to write safer code that avoids crashes from wrong type conversions.
Syntax
C Sharp (C#)
Type variable = object as Type;
bool check = object is Type;

as tries to convert and returns null if it fails.

is checks if the object is a certain type and returns true or false.

Examples
Using as to convert obj to a string safely.
C Sharp (C#)
object obj = "hello";
string s = obj as string;  // s will be "hello"
as returns null because obj is not a string.
C Sharp (C#)
object obj = 123;
string s = obj as string;  // s will be null
is checks the type and returns false here.
C Sharp (C#)
object obj = 123;
bool isString = obj is string;  // false
is returns true because obj is a string.
C Sharp (C#)
object obj = "hello";
bool isString = obj is string;  // true
Sample Program

This program shows how as returns the string or null, and how is checks the type and prints messages accordingly.

C Sharp (C#)
using System;

class Program
{
    static void Main()
    {
        object obj1 = "Hello World";
        object obj2 = 42;

        // Using 'as' operator
        string str1 = obj1 as string;
        string str2 = obj2 as string;

        Console.WriteLine(str1 ?? "obj1 is not a string");
        Console.WriteLine(str2 ?? "obj2 is not a string");

        // Using 'is' operator
        if (obj1 is string)
            Console.WriteLine("obj1 is a string");
        else
            Console.WriteLine("obj1 is NOT a string");

        if (obj2 is string)
            Console.WriteLine("obj2 is a string");
        else
            Console.WriteLine("obj2 is NOT a string");
    }
}
OutputSuccess
Important Notes

Remember, as only works with reference types or nullable types.

Using is is a quick way to check type before casting.

Using as avoids exceptions but you must check for null after.

Summary

as tries to convert and returns null if it can't.

is checks if an object is a certain type and returns true or false.

Both help write safer code when working with different types.