Is and as operators

Source: Internet
Author: User

The as operator has a certain range of applicability. It is only applicable to the reference type or the type that can be null, but cannot perform other conversions, such as value type conversion and custom type conversion, this type of conversion should be executed using a forced conversion expression. As returns NULL when the conversion fails. As does not throw an exception.

The is operator does not actually execute conversions. It only checks whether the specified object is compatible with the given type. To put it bluntly, it indicates whether the specified object can be converted to the given type.

Person P = new person (); p. id = 1; p. age = 23; p. name = "Zhang Fei"; object o = P; person p1 = O as person; console. writeline (p1.name); // output Zhang Fei can forcibly convert O to person type person p1 = new person (1, 20, "Zhang Fei"); person P2 = new person (2, 21, "Guan Yu"); person P3 = new person (3, 22, "Liu Bei"); List <person> personlist = new list <person> (); personlist. add (P1); personlist. add (P2); personlist. add (P3); object o = personlist; List <person> personlist1 = O as list <person>; console. writeline (personlist1 [1]. name); // output Guan Yu lecture o forced conversion list strong type set person P4 = new person (4, 24, "Zhao Yun"); object o = P4; console. writeline (P4 is person); // Output True list <person> personlist = new list <person> (); object O1 = personlist; console. writeline (O1 is person); // outputs false console. writeline (O1 is list <person>); // Output True

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.