C# as operator
In this chapter you will learn:
- What is C# as operator
- How to use as operator
- Example for as operator
- 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:
- What is IS operator
- Get to know is operator
- Example for C# is operator
- How to use is operator with interface
- Use 'is' to avoid an invalid cast
- Runtime check with in keyword