Safe Type Casting with IS and AS Operator

Safe Type Casting with IS and AS Operator

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

To deepen your understanding of type casting and other C# concepts, be sure to enroll in our Free C Sharp Course for a comprehensive learning experience.

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:

I hope you will enjoy the tips while programming with C#. I would like to have feedback from my blog readers. Your valuable feedback, questions, or comments about this article are always welcome. Also, Consider our C# Programming Course for a better understanding of all C# concepts

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
Azure AI Engineer Certification Training
20 Sep
07:00AM - 09:00AM IST
Checkmark Icon
Get Job-Ready
Certification
Azure AI & Gen AI Engineer Certification Training Program
20 Sep
07:00AM - 09:00AM IST
Checkmark Icon
Get Job-Ready
Certification
Advanced Full-Stack .NET Developer with Gen AI Certification Training
21 Sep
07:00AM - 09:00AM IST
Checkmark Icon
Get Job-Ready
Certification
ASP.NET Core Certification Training
21 Sep
07:00AM - 09:00AM IST
Checkmark Icon
Get Job-Ready
Certification
Azure DevOps Certification Training
24 Sep
08:30PM - 10:30PM IST
Checkmark Icon
Get Job-Ready
Certification
Accept cookies & close this