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”.

class Shape{}
class Circle : Shape{}
class Rectangle : Shape { }

//Test IS : if object is circle, "Circle" will be displayed or 
// "Not a Circle"
class Program
{
    static void Main(string[] args)
    {
        Shape sc = new Circle();
        DisplayShape(sc);

        Shape sr = new Rectangle();
        DisplayShape(sr);
        

    }
    public static void DisplayShape(Shape s)
    {
        if (s is Circle)
        {
            Console.WriteLine("Circle");
        }
        else
        {
            Console.WriteLine("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”.

public static void DisplayShape(Shape s)
    {
        Circle c = s as Circle;// Type cast from base to derived class circle.
       
        if (c != null)
        {
            Console.WriteLine("Got Circle Object");
        }
        else
        {
            Console.WriteLine("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.

public static void DisplayShape(Shape s)
    {
        Circle c = (Circle )s;// Type cast from base to derived class circle.
       
        if (c != null)
        {
            Console.WriteLine("Got Circle Object");
        }
        else
        {
            Console.WriteLine("Not a Circle Object");
        }      
    }

Related Posts