Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Daniel Solis - Illustrated C# 2010 - 2010.pdf
Скачиваний:
16
Добавлен:
11.06.2015
Размер:
11.23 Mб
Скачать

CHAPTER 18 CONVERSIONS

The is Operator

As shown previously, some conversion attempts are not successful and raise an InvalidCastException exception at run time. Instead of blindly attempting a conversion, you can use the is operator to check whether a conversion would complete successfully.

The syntax of the is operator is the following, where Expr is the source expression:

Returns a bool

Expr is TargetType

The operator returns true if Expr can be successfully converted to the target type through any of the following:

A reference conversion

A boxing conversion

An unboxing conversion

For example, in the following code, you use the is operator to check whether variable bill of type Employee can be converted to type Person, and then you take the appropriate action.

class Employee : Person

{ }

class Person

 

 

{

 

 

public string Name =

"Anonymous";

public int Age

=

25;

}

 

 

class Program

{

static void Main()

{

Employee bill = new Employee(); Person p;

// Check if variable bill can be converted to type Person if( bill is Person )

{

p = bill;

Console.WriteLine("Person Info: {0}, {1}", p.Name, p.Age);

}

}

}

The is operator can be used only for reference conversions and boxing and unboxing conversions. It cannot be used for user-defined conversions.

463

CHAPTER 18 CONVERSIONS

The as Operator

The as operator is like the cast operator, except that it does not raise an exception. If the conversion fails, rather than raising an exception, it returns null.

The syntax of the as operator is the following, where

Expr is the source expression.

TargetType is the target type, which must be a reference type.

Returns a reference

Expr as TargetType

Since the as operator returns a reference expression, it can be used as the source for an assignment. For example, variable bill of type Employee is converted to type Person, using the as operator, and

assigned to variable p of type Person. You then check to see whether p is null before using it.

class Employee : Person { }

class Person

{

public

string Name =

"Anonymous";

public

int Age

=

25;

}

class Program

{

static void Main()

{

Employee bill = new Employee(); Person p;

p = bill as Person; if( p != null )

{

Console.WriteLine("Person Info: {0}, {1}", p.Name, p.Age);

}

}

}

Like the is operator, the as operator can be used only for reference conversions and boxing conversions. It cannot be used for user-defined conversions or conversions to a value type.

464

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]