C#: Casting with parentheses versus casting with as

By lxcid

I always seems to forgot the differences between casting with parentheses

Control c = FindControl( "TextBoxControl" );
TextBox tb = ( TextBox ) c; // Throws an exception if fails.

versus casting with as

Control c = FindControl( "TextBoxControl" );
TextBox tb = c as TextBox; // Return null if fails.

Here’s the differences:

  • Casting with as can only be done on reference type.
  • On event of a conversion failure, casting with parentheses will raises an exception, while casting with as will yields a null.
  • expression as type
    is equivalent to:
    expression is type ? (type)expression : (type)null
    except that expression is evaluated only once.

Reference:

Tags: , , , , , , ,

Leave a Reply