
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
138
|
Chapter 3: Classes and Structures
or:
checked
{
short destination = 0;
int source = Int32.MaxValue;
destination = (short)source;
}
This code throws an OverflowException exception if any loss of information would
occur. This allows the application to be notified of the overflow condition and to
handle it properly.
The
Convert method is always considered to operate in a checked context, even when
no other type of checked context wraps the code performing the conversion.
See Also
See the “checked Keyword,” “unchecked Keyword,” “Checked and Unchecked,” and
“Convert Class” topics in the MSDN documentation.
3.13 Determining When to Use the Cast Operator,
the as Operator, or the is Operator
Problem
You need to determine which operator is best in your situation—the cast (type)
operator, the as operator, or the is operator.
Solution
Use the information provided in the Discussion section to determine which operator
is best to use.
Discussion
Use the cast operator when:
• You are casting a reference type to a reference type.
• You are casting a value type to a value type.
• You are performing a boxing or unboxing conversion.
• You are invoking a user-defined conversion. The
is and as operators cannot
handle this type of cast.
Use the
as operator when:
•Itisnot acceptable for the
InvalidCastException to be