As keyword in C# with Example

As keyword in C# with Example
As keyword in C# with Example

We have seen how to use is operator before type casting.  Another way to check whether type casting was successful or not, is as keyword.  If the type casting was successful, reference variable point to that object in memory.  If the type casting was failed, then reference variable contains a null value.  So before execution of further code, you can check for reference variable value and can easily avoid any kind of runtime errors.

Easy way to remember when to use is operator and as keyword:

  • Is Operator:  First check and then type cast.
  • As keyword:  First type cast and then check.
using System;

namespace Hello
{   
    //Employee Class
     class Employee
    {
        public void PrintName()
        {
            Console.WriteLine("This is an Employee Class.");
        }

    }

    //Manager Class
    class Manager:Employee
    {
        public new void PrintName()
        {
            Console.WriteLine("This is a Manager Class.");
        }

    }

    class Program
    {
        static void Main(string[] args)
        {
            Manager man = new Manager();

            Employee emp = man as Employee;
          
          if(emp != null)
          {             
              emp.PrintName();
          }         
                       
        }            
    }
}

 Output:

This is an Employee Class.
Press any key to continue . . .