Conversion Using the as OperatorThe advantage of the is operator is that it enables verification that a data item is of a particular type. The as operator goes one step further. It attempts a conversion to a particular data type just like a cast does. In contrast to a cast, however, the as operator assigns null to the target if the conversion is unsuccessful. This is significant because it avoids the exception that could result from casting. Listing 6.23 demonstrates using the as operator. Listing 6.23. Data Conversion Using the as Operator
By using the as operator, you are able to avoid additional try-catch handling code if the conversion is invalid because the as operator provides a way to attempt a cast without throwing an exception if the cast fails. One advantage of the is operator over the as operator is that the latter cannot successfully determine the underlying type. The latter potentially casts up or down an inheritance chain, as well as across to types supporting the cast operator. Therefore, unlike the as operator, the is operator can determine the underlying type. |