Mega Code Archive

 
Categories / C# Book / 01 Language Basics
 

0147 as operator

as operator does the down cast. Rather than throws exception out it assigns the reference to null. using System; 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; 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: successful