CSharp - Use of the "as" Keyword

Introduction

as keyword can cast the given object to the specified type if it is cast able; otherwise, it will return null.

as keyword can do both the cast-ability check and the conversion/transformation.

Demo

using System;

class Program/*from w ww  .j av a2s.  c  o  m*/
{
    class Shape
    {
        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");
        }
    }
    static void Main(string[] args)
    {
        Shape shapeOb = new Shape();
        Circle circleOb = new Circle();
        Rectangle rectOb = new Rectangle();
        circleOb = shapeOb as Circle; //no exception
        if (circleOb != null)
        {
            circleOb.ShowMe();
        }
        else
        {
            Console.WriteLine("'shapeOb as Circle' is prodcuing null ");
        }
        shapeOb = rectOb as Shape;
        if (shapeOb != null)
        {
            Console.WriteLine("'rectOb as Shape' is NOT prodcuing null ");
            shapeOb.ShowMe();
        }
        else
        {
            Console.WriteLine(" shapeOb as Circle is prodcuing null ");
        }
    }
}

Result

Note

The operator as does the conversion automatically if the operation is cast-able; otherwise, it returns null.

as operator will do the downcast operation successfully or it will evaluate to null if the downcast fails.

Related Topic