CSharp - Inheritance is operator

Introduction

is operator tests whether a reference derives from a specified class or implements an interface.

It is often used to test before downcasting.

Suppose we have the following class

class Shape{
       public string Name;
}

class Circle : Shape   // inherits from Shape
{
       public long Radius;
}

class Square : Shape   // inherits from Shape
{
       public decimal Width;
}

The following code check a is an Circle object.

Shape a = new Shape();
Circle s = a as Circle;       // s is null; no exception thrown

if (a is Circle)
    Console.WriteLine (((Circle)a).Radius);

Related Topics