C # type conversion during daily training

Source: Internet
Author: User

A basic knowledge, but not everyone can make it clear.

When a subclass object is converted to a parent class, it can be implicitly converted.
When a parent class object is converted to a subclass, the conversion must be displayed. If the actual object to which the parent class type points is a parent class object rather than a subclass object, the runtime error invaildcastexception occurs.

Use the as operator to avoid invalidcastexception, but return NULL if the conversion fails.

Mytypea =   New Mytypea ();

Mytypeb B1
= (Mytypeb);
Mytypeb B2
= A As Mytypeb;

Mytypeb is a subclass of mytypea. The second sentence will cause invalidcastexception, while the third sentence will not make an error, but B2 is a null reference.

There is also an is operator, which can determine whether the type of the object actually referenced by the variable is a specified type. Note that it is the actually referenced object type, regardless of whether the reference is an abstract class or an interface.
When a null value is actually referenced, a false value is returned.

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.