Safe conversion of data types in the original C # (Is,as)
The following code, which cannot be boxed, has an error forcing the type conversion because it is not possible to convert it to an int type, since C is the class type. Although the compiler can compile, runtime throws a InvalidCastException exception at run time.
Circle C = New Circle (8); Object o = C; This clause is correct, but will not be boxed, because boxing is from the stack to the heap, the value type is required, and C is the reference type int i = (int) o;//compile succeeded //compiler compile pass, but runtime runtime throws a Invalidcastexc Eption
is and as are operators that C # provides for performing type casts in a safe manner, using the following usage.
The is operator verifies that the object's type is not what it wants.
Wrappedint WI = new Wrappedint (); Object o = wi; If (O is Wrappedint) { Wrappedint temp = (wrappedint) o; Transition is secure, O has been determined to be a wrappedint }
The as operator takes an object and a type as its left and right operands.
Runtime attempts to convert the object to the specified type, and if the conversion succeeds , returns The result of the successful conversion to temp, and returns null to Temp if the conversion fails .
Wrappedint WI = new Wrappedint (); Object o = wi; Wrappedint temp = o as wrappedint; The transition is secure, O is determined to be a wrappedint if (temp! = null) { //Only the conversion succeeds, the code here can be executed }
Security transformations for data types in C # (Is,as)