Skip to Content
C# Cookbook
book

C# Cookbook

by Stephen Teilhet, Jay Hilyard
January 2004
Beginner to intermediate
864 pages
22h 18m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook

3.14. Determining Whether to Use theCast Operator, the as Operator, or theis 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

The cast operator should be used when:

  • It is acceptable for the InvalidCastException to be thrown. To prevent this exception from being thrown, consider using either the as or is operators.

  • 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.

The as operator should be used 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.

The is operator should be used 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 ...

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.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
ASP.NET Cookbook

ASP.NET Cookbook

Michael A Kittel, Geoffrey T. LeBlond

Publisher Resources

ISBN: 0596003390Supplemental ContentCatalog PageErrata