C # basic type conversion

Source: Internet
Author: User
  class  preson 
{< br> Public int I = 30 ;
Public int N = 40 ;
Public int Add ( int A, int B)
{< br> return A + B;
}< br> class water: preson
{< br> Public int cut ( int B, int C)
{< br> return B-C;
}< br>
}
ClassProgram
{
Static VoidMain (String[] ARGs)
{
Preson P =NewWater (); // can be converted to the parent type
P. Add (2,4);
 
Water S = (water) New preson (); // the code can be compiled. An error occurs during runtime and the parent type cannot be converted to the child type. Invalidcastexception Error
Water W =NewWater (); // After conversion, all common methods, fields, and attributes of the parent class can be accessed.
 
W. Cut (2,3);
 
Bool isbol = (W is preson); // The is Operator returns the bool value. No exception is thrown. True is returned here.

Preson pp = new preson ();
Bool isbol = (PP is water); // it won't work here

 preson Pr = w as preson; // CLR checks whether W is compatible with the preson type. If yes, a non-null reference of the same object is returned. Otherwise, null is returned. The as operator works in the same way as forced type conversion, but it does not throw an exception. If the object cannot be converted, the result is null. 

}< BR >}

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.