
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Casting with the as Operator
|
141
This method allows a System.Drawing.Point structure to be cast to an object of type
MyPoint. Due to the use of the explicit keyword, the cast must be explicitly defined:
System.Drawing.Point systemPt = new System.Drawing.Point(0, 0);
MyPoint pt = (MyPoint)systemPt;
If you attempt to use the as operator in a user-defined conversion, the following
compiler error is shown:
Cannot convert type 'MyPoint' to 'Point' via a built-in conversion
This type of conversion does not work with unboxing conversions, either. An unbox-
ing conversion converts a previously boxed value type to its original value type, such
as with the following code:
int x = 5;
object obj = x; // Box x
int originalX = obj as int; // Attempt to unbox obj into an integer.
If you attempt to use the as operator in an unboxing conversion, the following com-
piler error is shown:
The as operator must be used with a reference type ('int' is a value type)
This is illegal because as indicates that the cast cannot be performed by returning
null, but there is no such thing as a null value for an int.
The
as operator cannot be used with a type parameter T when T could be a struct, for
the same reason as previously mentioned. The following code will not compile:
public class TestAsOp<T>
{
public T ConvertSomething(object ...