Safe Type Casting with IS and AS Operator

Safe Type Casting with IS and AS Operator

19 Sep 2025
Intermediate
114K Views
8 min read
Learn with an interactive course and practical hands-on labs

Best Free C# Course: Learn C# In 21 Days

Type Casting: An Overview

Type Casting is the mechanism to convert one data type to another. While typecasting one data type to another, we get exceptions if the previous data type is not compatible with the new data type. To avoid this exception, we have IS and AS operators in C# for safe type casting.

In this C# Tutorial, we will explore more about C Sharp Safe Type Casting with IS and AS Operator which will include What is 'IS' Operator in C#, What an is 'AS' operator in C#, the difference between 'IS' and 'AS' operator, and safe typecasting with as operator. Entry-level C# developers earn up to $13,000 more annually. Kickstart your journey with our Free C# Certification now!

IS Operator

  • The IS operator checks whether the type of a given object is compatible with the new object type.
  • It returns a boolean type value: true if the given object is compatible with a new one, else false.
  • In this way IS operators help you to do safe type casting.

Example of IS Operator

 if(obj is Employee)

{
   // to check an object is a type of my custom class type:
} 

Use of IS Operator:

1. To check the run-time type of an expression
 int i = 44;
object iBoxed = i;
int? jNullable = 42;
if (iBoxed is int a && jNullable is int b)
{
    Console.WriteLine(a + b);  // output 86
}
2. To check for null
 if (input is null)
{
    return;
}
3. To check for non-null
 if (result is not null)
{
    Console.WriteLine(result.ToString());
}
4. To match elements of a list or array
 int[] empty = [];
int[] one = [1];
int[] odd = [1, 3, 5];
int[] even = [2, 4, 6];
int[] fib = [1, 1, 2, 3, 5];

Console.WriteLine(odd is [1, _, 2, ..]);   // false
Console.WriteLine(fib is [1, _, 2, ..]);   // true
Console.WriteLine(fib is [_, 1, 2, 3, ..]);     // true
Console.WriteLine(fib is [.., 1, 2, 3, _ ]);     // true
Console.WriteLine(even is [2, _, 6]);     // true

Note

  1. If the reference of the given object is null, the IS operator will return false since there is no object available to check its type.

Read More - C# Interview Questions For Freshers

AS Operator

  • The AS operator also checks whether the type of a given object is compatible with the new object type.
  • It returns non-null if the given object is compatible with a new one, else null.
  • In this way AS operators help you to do safe type casting. The below code can be rewritten by using the AS operator in a better way.
  • Let's see safe typecasting with the AS operator in C# Complier.

Syntax:

 int itype = item as int;

Example of AS Operator

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AsOperator
{
    public class Employee { }
    public class Student { }
    public class College : Student { }
    class Program
    {
        static void Main(string[] args)
        {
            Student s = new Student();
            Employee e = new Employee();
            College c = new College();
            System.Collections.ArrayList list = new System.Collections.ArrayList();
            list.Add("Dotnetricks As Scholarhat");
            list.Add("12345");
            list.Add(s);
            list.Add(e);
            list.Add(c);
            foreach (object item in list)
            {
                // Try to convert item as a string
                string stype = item as string;

                if (stype != null)
                    Console.WriteLine(item.ToString() + " converted successfully.");
                else
                    Console.WriteLine(item.ToString() + " conversion failed.");
            }
            Console.ReadLine();
        }
    }
} 

Output

 Dotnetricks As Scholarhat converted successfully.
12345 converted successfully.
AsOperator.Student conversion failed.
AsOperator.Employee conversion failed.
AsOperator.College conversion failed.

Note

  1. If the reference of the given object is null, the AS operator will return NULL since there is no object available to check its type.

  2. AS operator performs only reference conversions, nullable conversions, and boxing conversions. This operator cannot perform other conversions such as user-defined conversions.

Conclusion:

Safe type casting using the is and as operators in C# helps developers avoid runtime exceptions and write safer, more reliable code. The is operator is best for checking whether an object is compatible with a given type before performing a cast.  The as operator attempts to cast an object to a specific type and returns null if the cast fails, preventing InvalidCastException. 

The tech industry needs full-stack .NET experts, with 22% job growth projected by 2026. Join our Full-Stack .NET Developer Certification and lead the way!

FAQs

The is operator is used for only reference, boxing, and unboxing conversions whereas as operator is used only for nullable, reference, and boxing conversions.

IS Operator. The IS operator checks whether the type of an given object is compatible with the new object type.

The as operator explicitly converts the result of an expression to a given reference or nullable value type.

Take our Csharp skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

GET FREE CHALLENGE

Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at ScholarHat)

He is a renowned Speaker, Solution Architect, Mentor, and 10-time Microsoft MVP (2016–2025). With expertise in AI/ML, GenAI, System Design, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development, he bridges traditional frameworks with next-gen innovations.

He has trained 1 Lakh+ professionals across the globe, authored 45+ bestselling eBooks and 1000+ technical articles, and mentored 20+ free courses. As a corporate trainer for leading MNCs like IBM, Cognizant, and Dell, Shailendra continues to deliver world-class learning experiences through technology & AI.
Live Training - Book Free Demo
ASP.NET Core Certification Training
25 Oct
08:00PM - 10:00PM IST
Checkmark Icon
Get Job-Ready
Certification
Advanced Full-Stack .NET Developer with Gen AI Certification Training
25 Oct
08:00PM - 10:00PM IST
Checkmark Icon
Get Job-Ready
Certification
.NET Solution Architect Certification Training
26 Oct
08:30PM - 10:30PM IST
Checkmark Icon
Get Job-Ready
Certification
.NET Microservices Certification Training
26 Oct
08:30PM - 10:30PM IST
Checkmark Icon
Get Job-Ready
Certification
Azure AI & Gen AI Engineer Certification Training Program
30 Oct
08:30PM - 10:30PM IST
Checkmark Icon
Get Job-Ready
Certification
Accept cookies & close this