Safe Type Casting with IS and AS Operator

Safe Type Casting with IS and AS Operator

23 May 2024
Intermediate
112K Views
7 min read
Learn with an interactive course and practical hands-on labs

Free C# Foundation 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.

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 by DotNetTricks)

Shailendra Chauhan, Founder and CEO of ScholarHat by DotNetTricks, is a renowned expert in System Design, Software Architecture, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development. His skill set extends into emerging fields like Data Science, Python, Azure AI/ML, and Generative AI, making him a well-rounded expert who bridges traditional development frameworks with cutting-edge advancements. Recognized as a Microsoft Most Valuable Professional (MVP) for an impressive 9 consecutive years (2016–2024), he has consistently demonstrated excellence in delivering impactful solutions and inspiring learners.

Shailendra’s unique, hands-on training programs and bestselling books have empowered thousands of professionals to excel in their careers and crack tough interviews. A visionary leader, he continues to revolutionize technology education with his innovative approach.
Accept cookies & close this