CSharp - Use keyword is

Introduction

The keyword is compares with a given type and returns true if casting is possible, otherwise, it returns false.

The following code has used three different shapes: triangle, rectangle, and circle.

We are storing the different shapes in an array, and then counting the total in each category.

When we go through each of them, we can manipulate whether they are a Circle, a Rectangle, or a Triangle object.

Demo

using System;

class Shape/*from  ww  w.j  av  a 2s . c o m*/
{
    public void ShowMe()
    {
        Console.WriteLine("Shape.ShowMe");
    }
}
class Circle : Shape
{
    public void Area()
    {
        Console.WriteLine("Circle.Area");
    }
}
class Rectangle : Shape
{
    public void Area()
    {
        Console.WriteLine("Rectangle.Area");
    }
}
class Triangle : Shape
{
    public void Area()
    {
        Console.WriteLine("Triangle.Area");
    }
}

class Program
{
    static void Main(string[] args)
    {
        int noOfCircle = 0, noOfRect = 0, noOfTriangle = 0;

        //Creating 2 different circle object
        Circle circleOb1 = new Circle();
        Circle circleOb2 = new Circle();
        //Creating 3 different rectangle object
        Rectangle rectOb1 = new Rectangle();
        Rectangle rectOb2 = new Rectangle();
        Rectangle rectOb3 = new Rectangle();
        //Creating 1 Triangle object
        Triangle triOb1 = new Triangle();
        Shape[] shapes = { circleOb1, rectOb1, circleOb2, rectOb2, triOb1, rectOb3 };
        for (int i = 0; i < shapes.Length; i++)
        {
            if (shapes[i] is Circle)
            {
                noOfCircle++;
            }
            else if (shapes[i] is Rectangle)
            {
                noOfRect++;
            }
            else
            {
                noOfTriangle++;
            }
        }
        Console.WriteLine("No of Circles in shapes array is {0}", noOfCircle);
        Console.WriteLine("No of Rectangles in shapes array is {0}", noOfRect);
        Console.WriteLine("No of Triangle in shapes array is {0}", noOfTriangle);
    }
}

Result

Related Topic