C # syntax exercise (4): type conversion

Source: Internet
Author: User
Use the convert class:
 
Toboolean-> bytes-> bytetochar-> chartodatetime-> bytes-> decimaltodouble-> doubletoint16-> optional toint32-> inttoint64-> bytes-> floattostring-> stringtouint16-> ushorttouint32 -> uinttouint64-> ulong
 
Using system; Class myclass {static void main () {int num; string STR; num = 99; STR = convert. tostring (Num); console. writeline (STR); STR = "123"; num = convert. toint32 (STR); console. writeline (Num); console. readkey ();}}

  

Implicit conversion:

Using system; Class myclass {static void main () {byte n = byte. maxvalue; short n1 = N; int n2 = N; long N3 = N; console. writeline ("{0}, {1}, {2}", N1, N2, N3); // 255,255,255 console. readkey ();}}

  

Display conversion, data may be lost due to overflow:

 
Using system; Class myclass {static void main () {ulong n = ulong. maxvalue; Byte N1 = (byte) N; ushort n2 = (ushort) N; uint N3 = (uint) N; console. writeline ("{0}, {1}, {2}", N1, N2, N3); // 4294967295, console. readkey ();}}

  

Overflow check:

Using system; Class myclass {static void main () {int I; byte B; I = 255; B = (byte) I;/* I is within the byte range, no overflow */B = unchecked (byte) I);/* same line, no overflow check */console. writeline (B); // 255 I ++; B = (byte) I;/* I is out of the byte range and will overflow */B = unchecked (byte) i);/* the same line as the previous line without any overflow check */console. writeline (B); // 0 I = 255; B = checked (byte) I);/* overflow detection */console. writeline (B); // 255 I ++; B = checked (byte) I);/* overflow detection fails and an error is reported */console. writeline (B); console. readkey ();}}

  

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.