10.7. The as operator

The as operator is a convenient shortcut in C# not found in Java. It can be viewed as the is operator combined with a type cast. It is used like this:

<expression> as <type>

First as checks if the <expression> can be cast into <type> – another way to phrase this is that a check is made to see if (<expression> is <type>) is true. If so, it casts <expression> to <type>, and then returns the result of the cast. If casting is not possible, the operator returns null. Study this example:

 1: using System;
 2:
 3: class Parent {}
 4: class Child:Parent {}  // Child extends Parent
 5:
 6: class MainClass{
 7:   public static void Main(){
 8:     Child c = new Child();
 9:     Parent p = c
						as Parent; 10: 11: if (p==null) 12: Console.WriteLine("cast ...

Get From Java to C#: A Developer's Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.