Conversion Using the as Operator


Conversion Using the as Operator

The 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

 object Print(IDocument document) {   if(thing != null)   {        // Print document...   }   else   {    } } static void Main() {   object data;    // ...     Print( data as Document ); } 

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.




Essential C# 2.0
Essential C# 2.0
ISBN: 0321150775
EAN: 2147483647
Year: 2007
Pages: 185

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