O'Reilly logo

From Java to C#: A Developer's Guide by Heng Ngee Mok

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required