as operator
In this chapter you will learn:
Using as operator
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.
using System;//from j av a2s.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.
using System;// j a v a 2 s .co 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;
if (e == null)
{
Console.WriteLine("successful");
}
}
}
The output:
as an interface
The following code shows how to use the as Keyword to Work with an Interface.
using System;/* ja v a2 s. c om*/
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();
}
}
Next chapter...
What you will learn in the next chapter:
- Get to know is operator
- How to use is operator with interface
- Use 'is' to avoid an invalid cast
- Runtime check with in keyword
Home » C# Tutorial » Class