3.9. 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 converting a reference type to a reference type.
You are converting a value type to a value type.
You are performing a boxing or unboxing conversion.
You are invoking a user-defined conversion. The
isandasoperators cannot handle this type of cast.
Use the as operator when:
It is not acceptable for the
InvalidCastExceptionto be thrown. Theasoperator will instead return anullif the cast cannot be performed.You are converting a reference type to a reference type.
You are not casting a value type to a value type. The cast operator must be used in this case.
You are performing a boxing conversion.
You are not performing an unboxing conversion. The cast operator must be used in this case unless the unboxing is to a
nullabletype.You are not invoking a user-defined conversion. The cast operator must be used in this case.
You are performing a cast to a type parameter
Tthat can be only a reference type. This is because anullmay be returned after evaluating this expression.
Use the is operator when:
You need a fast method of determining whether using the
asoperator will returnnullbefore it is attempted.You do not need to actually ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access