When to use IS and AS operators in C#?

(Last Updated On: February 25, 2019)

Answer: Use IS Operator in C# to check if two objects are of same type and AS Operator in C# to typecast one type of object to the other type.

IS OPERATOR

  • Used to compare two objects of same type.
  • Returns Boolean value true if two object are of same type or else false.
  • Returns false for null object.

IS Operator Example

In below main program, we will construct objects for both Circle and Rectangle and call DisplayShape(Shape s) method. This method checks if shape object is of same type of Circle and if it is same then it will return true and print “Circle” or else “ Not a Circle”.

 

 

AS OPERATOR

  • Used to safe typecasting from one object type to other type.
  • Returns type casted object or else null if type cast fails.
  • No exception when cast fails but null.

AS Operator Example

Let’s modify the DisplayShape(Shape s)to typecast base class Shape object to derived class Circle object.(just replace DisplayShape() in above program to test AS operator)

If typecast is successful it will print “Got Circle Object” and if fails it will print “Not a Circle Object”.

 

 

NOTE: We can also typecast object as Circle c = (Circle )s instead of Circle c = s as Circle; as shown below and it will work. But, if Shape object s is other than that of Circle, program will crash. Hence, using AS operator here will be better.