C# as operator
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 . j ava 2 s.c om*/
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.
// w w w. j av a2s . 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.