Month End Sale: Get Extra 10% OFF on Job-oriented Training! Offer Ending in
D
H
M
S
Get Now
Safe Type Casting with IS and AS Operator

Safe Type Casting with IS and AS Operator

23 May 2024
Intermediate
111K Views
7 min read
Learn via Video Course & by Doing Hands-on Labs

Free C# Course Online

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

Q1. What is the difference between is and as operator in C#?

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

Q2. How to do safe type casting in C#?

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

Q3. What is the value type of as operator in C#?

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

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
Software Architecture and Design Training Jul 28 SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
.NET Solution Architect Certification Training Jul 28 SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
Azure Developer Certification Training Jul 28 SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification Training Jul 28 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
ASP.NET Core Certification Training Jul 28 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
Data Structures and Algorithms Training with C# Jul 28 SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
Microsoft Azure Cloud Architect Aug 11 SAT, SUN
Filling Fast
03:00PM to 05:00PM (IST)
Get Details
Angular Certification Course Aug 11 SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
ASP.NET Core Project Aug 24 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details

Can't find convenient schedule? Let us know

About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this