Security transformations for data types in C # (Is,as)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.