Changing an explicit cast-expression to an ‘as’ operator and back
Objects can be converted from one type to another, assuming that the types are compatible. Often this is achieved using implicit conversion or explicitly with the cast operator. To perform an explicit casting, there are two approaches used:
- a cast-expression
- an ‘as’ operator
A cast-expression is used to explicitly convert an expression to a given type. The cast operation forces the conversion, possibly losing some data along the way. Care must be taken, as it is possible to cause a run-time error, or receive unpredictable results when the destination casting type is too small to receive a large value of the cast expression.
The ‘as’ operator is used to explicitly convert a value to a given reference type or nullable type. Unlike the cast expression, the ‘as’ operator never throws an exception. Instead, if the indicated conversion is not possible, the resulting value is null.
To convert between explicit type cast approaches, you can use two code providers shipped in CodeRush Pro:
Use Implicit type cast
Converts an explicit type cast expression into an ‘as’ operator expression:
Use Explicit type cast
Converts an ‘as’ operator expression into an explicit type cast expression:
These code providers work in Visual Basic as well as in C#, using VB TryCast and CType operators.
—– Products: CodeRush Pro Versions: 11.2 and up VS IDEs: 2008 and up Updated: Feb/16/2012 ID: C157