Recipe3.13.Determining When to Use the Cast Operator, the as Operator, or the is Operator


Recipe 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 situationthe 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:

  • It is not acceptable for the InvalidCastException to be thrown. The as operator will instead return a null if the cast cannot be performed.

  • You are casting 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.

  • 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 T that can be only a reference type. This is because a null may be returned after evaluating this expression.

Use the is operator when:

  • You need a fast method of determining whether a cast can be performed before the actual cast is attempted.

  • You do not need to actually cast a variable from one data type to another; you just need to determine if the variable can be cast to a specific type.

  • It is not acceptable for the InvalidCastException to be thrown.

  • You are casting 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 not invoking a user-defined conversion. Unlike the as operator, a compile-time error is not displayed when using the is operator with a user-defined conversion. This is operator will instead always return a false value, regardless of whether the cast can successfully be performed.

See Also

See Recipes 3.14 and 3.15; see the "( ) Operator," "as Operator," and "is Operator" topics in the MSDN documentation.



C# Cookbook
Secure Programming Cookbook for C and C++: Recipes for Cryptography, Authentication, Input Validation & More
ISBN: 0596003943
EAN: 2147483647
Year: 2004
Pages: 424

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net