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 failed");
13:     else{
14:       Console.WriteLine("cast successful");
15:     }
16:   }
17: }

Output:

c:expt>test
cast successful

Assuming that a is a reference variable which we want to check, the two methods below are functionally identical:

40: // implementation 1: using is operator
41: public MyClass PerformCast(object a){
42:   if (a is MyClass)
43:     return (MyClass)a;
44:   else
45:     return null;
46: }

40: // implementation 2: using as operator
41: public MyClass PerformCast(object a){
42:   return a as MyClass;
43: }

Using the as operator for this purpose is obviously more efficient.

If it is known during compile time that the as operator is used to attempt to perform an invalid cast, a compiler error will be produced. The following code fragment will not compile, because there is no way that i can be cast into a string, and this fact is known during compile time:

int i = 99;
string s = i as string;

On the other hand, the following fragment compiles fine because it is possible that o be reassigned to refer to a string object during runtime:

object o = 99;
string s = o as string;

During runtime, s is assigned a null value, because the casting cannot be performed. Figure 10.3 summarizes how the as operator works.

Figure 10.3. Activity diagram showing the flow of action for the as operator.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.151.220