C# as operator

In this chapter you will learn:

  1. What is C# as operator
  2. How to use as operator
  3. Example for as operator
  4. How to use as operator with interface

Description

The as operator performs a downcast that evaluates to null (rather than throwing an exception) if the downcast fails.

Syntax

as operator does the down cast. Rather than throws exception out it assigns the reference to null.

The general form:

expr as type

expr is the expression being cast to type. On succeed, a reference to type is returned. Otherwise, a null reference is returned.

Example

Example for as operator


using System;/* w  w w . jav  a2 s. c  o m*/
class Person
{
    public string name;
}
class Employee : Person
{
    public string companyName;
}

class Program
{
    static void Main(string[] args)
    {
        Person p = new Person();

        Employee e = p as Employee;
       
    }
}

After the as operator we can use if statement to check the result.

The code above generates the following result.

as an interface

The following code shows how to use the as Keyword to Work with an Interface.


//from   w  w w  .  j  a v a2  s .c  o m
using System;
   
public interface IPrintMessage
{
    void Print();
};
   
class Class1
{
    public void Print()
    {
        Console.WriteLine("Hello from Class1!");
    }
}
   
class Class2 : IPrintMessage
{
    public void Print()
    {
        Console.WriteLine("Hello from Class2!");
    }
}
   
class MainClass
{
    public static void Main()
    {
        PrintClass   PrintObject = new PrintClass();
   
        PrintObject.PrintMessages();
    }
}
   
class PrintClass
{
    public void PrintMessages()
    {
        Class1      Object1 = new Class1();
        Class2      Object2 = new Class2();
   
        PrintMessageFromObject(Object1);
        PrintMessageFromObject(Object2);
    }
   
    private void PrintMessageFromObject(object obj)
    {
        IPrintMessage PrintMessage;
   
        PrintMessage = obj as IPrintMessage;
        if(PrintMessage != null)
            PrintMessage.Print();
    }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. What is IS operator
  2. Get to know is operator
  3. Example for C# is operator
  4. How to use is operator with interface
  5. Use 'is' to avoid an invalid cast
  6. Runtime check with in keyword
Home »
  C# Tutorial »
    C# Types »
      C# Inheritance
C# Class Inheritance
C# base Keyword
C# seal Functions and Classes
C# Abstract Classes and Abstract Members
C# Polymorphism
C# Virtual Function Members
C# Override methods
C# Shadow inherited members
C# as operator
C# is operator