Friday, June 14, 2013

Using "as" Operator in C#

Using as
Sometimes you will want to try a conversion at runtime, but not throw an exception if the
conversion fails (which is the case when a cast is used). To do this, use the as operator,
which has this general form:
expr as type


Here, expr is the expression being converted to type. If the conversion succeeds, then a
reference to type is returned. Otherwise, a null reference is returned. The as operator can
be used to perform only reference, boxing, unboxing, or identity conversions.
The as operator offers a streamlined alternative to is in some cases. For example,
consider the following program that uses is to prevent an invalid cast from occurring:
// Use is to avoid an invalid cast.
using System;
class A {}
class B : A {}
class CheckCast {
static void Main() {
A a = new A();
B b = new B();
// Check to see if a can be cast to B.
if(a is B) // if so, do the cast
b = (B) a;
else // if not, skip the cast
b = null;
if(b==null)
Console.WriteLine("The cast in b = (B) a is NOT allowed.");
else
Console.WriteLine("The cast in b = (B) a is allowed");
}
}



This program displays the following output:
The cast in b = (B) a is NOT allowed.
As the output shows, since a is not a B, the cast of a to B is invalid and is prevented by the if
statement. However, this approach requires two steps. First, the validity of the cast must be
confirmed. Second, the cast must be made. These two steps can be combined into one through
the use of as, as the following program shows:

// Demonstrate as.
using System;
class A {}
class B : A {}
class CheckCast {
static void Main() {
A a = new A();
B b = new B();
b = a as B; // cast, if possible


if(b==null)
Console.WriteLine("The cast in b = (B) a is NOT allowed.");
else
Console.WriteLine("The cast in b = (B) a is allowed");
}
}
Here is the output, which is the same as before:
The cast in b = (B) a is NOT allowed.
In this version, the as statement checks the validity of the cast and then, if valid, performs
the cast, all in one statement.

Deference Taken By:Complelte Refrence

No comments:

Post a Comment

Your comment is pending for approval

AngularJS Basics - Part 1

                                                                  AngularJS What is AngularJS ·          Framework by googl...