Data type conversion in C #

Source: Internet
Author: User
Tags float double
Type conversion 
Display Conversion
Implicit conversion
Custom Conversion

(1) Implicit conversion : Generally, it is converted from low type to high type to ensure that the value does not change.
Implicit numeric conversion:  
Slave Sbyte to short, Int, long, float, double or decimal.
Slave Byte to short, ushort, Int, uint, long, ulong, float double or decimal.
Slave Short to int, long, float, double, or decimal.
Slave Ushort to int, uint, long, ulong, float, double, or decimal.
Slave Int to long, float, double, or decimal.
Slave Uint to long, ulong, float, double, or decimal.
Slave Long to float, double, or decimal.
Slave Ulong to float, double, or decimal.
Slave Char to ushort, Int, uint, long, ulong, float, double, or decimal.
Slave Float to double.
There is no implicit conversion to the char type, so the values of other integer types are not automatically converted to the char type.
The floating point type cannot be implicitly converted to the decimal type.

Implicit Enumeration Conversion
Implicit Enumeration conversion allows you to convert decimal integers0Convert to any enumeration type.

Implicit conversion
Conversion from a derived class to a base class
Implicit conversions refer to conversions between a type of reference types. Such conversions can always be successful, so no check is required at runtime.

Packing and conversion
Packing conversion allows implicit conversion of value type to reference type.

(2) Display conversion: Also known as forced type conversion. Data correctness cannot be guaranteed.
(Type)(Expression)

(3) Custom Conversion
All user-defined conversions are static.StaticKeywords
User-Defined conversion display and implicit display, they useImplicit(Implicit conversion) or Explicit(Display conversion) keyword declaration.
StaticAccess Rhetoric Conversion RhetoricOperatorConversion Type(Parameters)

Example :

Using system;
Struct number
{
Private int value;
Public number (INT value)
{
This. value = value;
}
// User-Defined integer Number Implicit type conversion
Static public implicit operator number (INT value)
{
Return new number (value );
}
// User-Defined Number Type to integer display Conversion
Static public explicit operator int (number N)
{
Return N. value;
}
// User-Defined Number Type String Implicit type conversion
Static public implicit operator string (number N)
{
Return N. tostring ();
}
}

Class Test
{
Static public void Main ()
{
Number N;
N = 10;
Console. writeline (INT) N );
//Implicit conversionString
Console. writeline (N );
}

Use System. Convert Class

Converts a basic data type to another basic data type.

Use Parse Method

Most pre-defined value types Use this static method to convert the corresponding text to the corresponding value type.

Packing and unboxing

PackingAndUnboxingMake the Value Type ObjectType conversion.

Boxing conversion allows you"Value Type"Implicit conversion"Reference Type". Set"Value Type"Value packing operations include:Allocate an object instanceAndSet"Value Type"Is copied to the instance..

Example:

In this example, the integer variableIConvert to object by packingO. In this example, the object retains the original copy of the content, that is123.

Using system;
Class testboxing
{
Public static void Main ()
{
Int I = 123;
Object o = I;// Implicit packing
I = 456;// Change variable I Value
Console. writeline ("the value-type value = {0}", I );// 456
Console. writeline ("the object-type value = {0}", O );// 123 Yes I Copy value
}
}
Cancel packing Conversion:Unboxing conversion allows explicit conversion of the reference type to the value type.

The unboxing operation includes the following two steps:First, check whether the instance of this object is a boxed value of a given value type., And thenCopy the value from the instance.
Example:

The following example illustrates how unboxing is invalid. Invalidcastexception . Use Try And Catch The error message is displayed when an error occurs.
Using system;
Public class unboxingtest
{
Public static void Main ()
{
Int inti= 123;
 Object o = Inti ;// Packing
Try
{
Int intj = (short) O ;// Unboxing is invalid, Short It is not a binning Value Type . Check whether the instance of this object is a boxed value of a given value type.
Console. writeline ("unboxing OK .");
}
Catch (invalidcastexception E)
{
Console. writeline ("{0} error: Incorrect unboxing.", e );
}
}

Other conversion Operators
As

As The operator is used to perform explicit type conversion of the reference type. If the type to be converted is compatible with the specified type, the conversion succeeds. If the type is not compatible, the system returns Null .
ExpressionAsType
AsThe operator is similar to type conversion. The difference is that when the conversion fails,AsThe operator returnsNullInstead of exception.
Example:
Object O1 = "somestring ";
Object O2 = 5;
String S1 = O1 as string;//Type compatibilityS1 = "somestring"
String S2 = O2 as string;// S2 = NULL

Is

IsThe operator is used to check whether the object type is compatible with the given type.(The object is of this type or is derived from this type.).
ExpressionIsType
Example:
Int I = 10;
If (I is object) // true
{}

Sizeof

SizeofOperators are used to obtainValue TypeIn bytes ).
Sizeof (Type)
SizeofThe operator applies only to the value type, not to the reference type.
SizeofThe operator can only be used Unsafe Mode.
Example:
Unsafe
{
Console. writeline ("{0}", sizeof (INT ));

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.