Click here to Skip to main content
15,881,204 members
Articles / Programming Languages / C#
Tip/Trick

Use of Is and As operators in C#

Rate me:
Please Sign up or sign in to vote.
3.29/5 (11 votes)
11 Mar 2013CPOL1 min read 86.3K   9   8
Solving the Type casting issue.

Introduction

Type casting is one of the unavoidable things in software development. In many situations we need to convert one object (Type) to another object (Type) and some times we get an exception like this: "Cannot implicitly convert type 'Object one' to 'object two'". To avoid this type of exceptions and check object compatibility, C# provides two operators namely is and as.

is operator

The is operator in C# is used to check the object type and it returns a bool value: true if the object is the same type and false if not.

For null objects, it returns false.

Syntax:

C#
bool isobject = (Object is Type);

Example:

C#
namespace IsAndAsOperators
{
    // Sample Student Class
    class Student
    {
        public int stuNo { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }

    }
    // Sample Employee Class
    class Employee
    {
        public int EmpNo { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public double Salary { get; set; }

    }
    class Program
    {

        static void Main(string[] args)
        {
            Student stuObj = new Student();
            stuObj.stuNo = 1;
            stuObj.Name = "Siva";
            stuObj.Age = 15;

            Employee EMPobj=new Employee();
            EMPobj.EmpNo=20;
            EMPobj.Name="Rajesh";
            EMPobj.Salary=100000;
            EMPobj.Age=25;

            // Is operator

            // Check Employee EMPobj is Student Type

            bool isStudent = (EMPobj is Student);
            System.Console.WriteLine("Empobj is a Student ?: {0}", isStudent.ToString());

            // Check Student stiObj is Student Typoe
            isStudent = (stuObj is Student);
            System.Console.WriteLine("Stuobj is a Student ?: {0}", isStudent.ToString());

            stuObj = null;
            // Check  null object Type
            isStudent = (stuObj is Student);
            System.Console.WriteLine("Stuobj(null) is a Student ?: {0}", isStudent.ToString());
            System.Console.ReadLine();
        }
    }

Output

Empobj is a Student ?: False
Stuobj is a Student ?: True 
Stuobj(null) is a Student ?: False

as operator

The as operator does the same job of is operator but the difference is instead of bool, it returns the object if they are compatible to that type, else it returns null.

Syntax:

C#
Type obj = Object as Type;

Example:

C#
namespace IsAndAsOperators
{
    // Sample Student Class
    class Student
    {
        public int stuNo { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }

    }
    // Sample Employee Class
    class Employee
    {
        public int EmpNo { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public double Salary { get; set; }

    }
    class Program
    {
        static void Main(string[] args)
        {
            Student stuObj = new Student();
            stuObj.stuNo = 1;
            stuObj.Name = "Praveen";
            stuObj.Age = 15;

            Employee EMPobj=new Employee();
            EMPobj.EmpNo=20;
            EMPobj.Name="Rajesh";
            EMPobj.Salary=100000;
            EMPobj.Age=25;     

            System.Console.WriteLine("Empobj is a Student ?: {0}", CheckAndConvertobject(EMPobj));

            System.Console.WriteLine("StuObj is a Student ?: {0}", CheckAndConvertobject(stuObj));
            System.Console.ReadLine();

        }

        public static string CheckAndConvertobject(dynamic obj)
        {
           // If obj is Type student it asign value to Stuobj else it asign null
            Student stuobj = obj as Student;
            if (stuobj != null)
                return "This is a Student and his name is " + stuobj.Name;

                return "Not a Student";         


        }
    }   
}

Output:

Empobj is a Student ?: Not a Student 
StuObj is a Student ?: This is a Student and his name is Praveen

Advantage of 'as' over 'is

In the case of is operator, to type cast, we need to do two steps:

  1. Check the Type using is
  2. If it’s true then Type cast

Actually this affects the performance since each and every time the CLR will walk the inheritance hierarchy, checking each base type against the specified type. To avoid this, use as it will do it in one step. Only for checking the type should we use the is operator.

History

  • Created on 23-01-2013.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 1 Pin
Olter12-Mar-13 0:52
Olter12-Mar-13 0:52 
GeneralMy vote of 1 Pin
nobodyxxxxx12-Mar-13 0:50
nobodyxxxxx12-Mar-13 0:50 
Questionnot Good Pin
praveensai23-Jan-13 18:41
praveensai23-Jan-13 18:41 
AnswerRe: not Good Pin
Rajasakthimaridasan23-Jan-13 19:08
Rajasakthimaridasan23-Jan-13 19:08 
GeneralMy vote of 1 Pin
Yaroslav Lobachevski23-Jan-13 13:43
Yaroslav Lobachevski23-Jan-13 13:43 
QuestionWaste of an article! Pin
FatCatProgrammer23-Jan-13 7:51
FatCatProgrammer23-Jan-13 7:51 
You have not added ANY knowledge. Anyone can google this or pick up any c# book and look at an example. I suggest you write something better and not waste time.
Relativity

AnswerRe: Waste of an article! Pin
Rajasakthimaridasan23-Jan-13 17:25
Rajasakthimaridasan23-Jan-13 17:25 
GeneralRe: Waste of an article! Pin
FatCatProgrammer24-Jan-13 4:08
FatCatProgrammer24-Jan-13 4:08 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.