Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C# Type Conversion

C# Type Conversion

In C#, type conversion is the process of converting a value of one data type to another data type.

Type conversions in C# can be divided into two types:Implicit type conversionandExplicit type conversion(also known as explicit casting).

Implicit type conversion

Implicit conversion is a conversion that does not require code to be written to specify it; the compiler performs it automatically.

Implicit conversion refers to converting a data type with a smaller range to one with a larger range; the compiler completes the conversion automatically. These conversions are performed by C# in a safe way by default and do not result in data loss.

For example, from int to long, from float to double, and so on.

Converting from a smaller integer type to a larger integer type, or from a derived class to a base class. Assigning a variable of type byte to a variable of type int is converted automatically by the compiler from byte to int, with no explicit conversion needed.

Example

byte

b

=

10

;

int

i

=

b

;

// implicit conversion, no explicit conversion needed

Assigning an integer to a long integer, or a floating-point number to a double-precision floating-point number, does not result in data loss:

Example

int

intValue

=

42

;

long

longValue

=

intValue

;

// implicit conversion, from int to long

Explicit conversion

Explicit type conversion, also called casting, must be explicitly specified by the programmer in the code.

Explicit conversion refers to converting a data type with a larger range to one with a smaller range, or converting one object type to another, which requires a cast operator to perform the conversion explicitly. Casting causes data loss.

For example, assigning a variable of type int to a variable of type byte requires explicit conversion.

Example

int

i

=

10

;

byte

b

=

(

byte

)

i

;

// explicit conversion, requires a cast operator

Casting to an integer type:

Example

double

doubleValue

=

3.14

;

int

intValue

=

(

int

)

doubleValue

;

// cast from double to int; data may lose its fractional part

Casting to a floating-point type:

Example

int

intValue

=

42

;

float

floatValue

=

(

float

)

intValue

;

// cast from int to float; data may lose precision

Casting to a string type:

Example

int

intValue

=

123

;

string

stringValue

=

intValue

.

ToString

(

)

;

// convert int to string

The following example shows an explicit type conversion:

Example

using

System

;

namespace

TypeConversionApplication

{

   

class

ExplicitConversion

   

{

       

static

void

Main

(

string

[

]

args

)

       

{

           

double

d

=

5673.74

;

           

int

i

;

           

// cast double to int

            i

=

(

int

)

d

;

            Console

.

WriteLine

(

i

)

;

            Console

.

ReadKey

(

)

;

           

       

}

   

}

}

When the code above is compiled and executed, it produces the following result:



5673

C# type conversion methods

C# provides the following built-in type conversion methods:

No. Method & Description
1 ToBoolean
Converts a type to a Boolean if possible.
2 ToByte
Converts a type to a byte type.
3 ToChar
Converts a type to a single Unicode character if possible.
4 ToDateTime
Converts a type (integer or string type) to a date-time structure.
5 ToDecimal
Converts a floating-point or integer type to a decimal type.
6 ToDouble
Converts a type to a double-precision floating-point number.
7 ToInt16
Converts a type to a 16-bit integer type.
8 ToInt32
Converts a type to a 32-bit integer type.
9 ToInt64
Converts a type to a 64-bit integer type.
10 ToSbyte
Converts a type to a signed byte type.
11 ToSingle
Converts a type to a small floating-point type.
12 ToString
Converts a type to a string type.
13 ToType
Converts a type to a specified type.
14 ToUInt16
Converts a type to a 16-bit unsigned integer type.
15 ToUInt32
Converts a type to a 32-bit unsigned integer type.
16 ToUInt64
Converts a type to a 64-bit unsigned integer type.

These methods are all defined in the System.Convert class and require including the System namespace when used. They provide a safe way to perform type conversions because they can handle null values and throw an exception if the conversion is not possible.

For example, use the Convert.ToInt32 method to convert a string to an integer:



string str = "123";

int number = Convert.ToInt32(str); // 转换成功,number为123

If the string is not a valid integer representation, Convert.ToInt32 throws a FormatException.

The following example converts values of different types to strings:

Example

using

System

;

namespace

TypeConversionApplication

{

   

class

StringConversion

   

{

       

static

void

Main

(

string

[

]

args

)

       

{

           

// define an integer variable

           

int

i

=

75

;

           

           

// define a floating-point variable

           

float

f

=

53

.

005f

;

           

           

// define a double-precision floating-point variable

           

double

d

=

2345.7652

;

           

           

// define a Boolean variable

           

bool

b

=

true

;

           

// convert the integer variable to a string and output it

            Console

.

WriteLine

(

i

.

ToString

(

)

)

;

           

           

// convert the floating-point variable to a string and output it

            Console

.

WriteLine

(

f

.

ToString

(

)

)

;

           

           

// convert the double-precision floating-point variable to a string and output it

            Console

.

WriteLine

(

d

.

ToString

(

)

)

;

           

           

// convert the Boolean variable to a string and output it

            Console

.

WriteLine

(

b

.

ToString

(

)

)

;

           

// wait for the user to press a key before closing the console window

            Console

.

ReadKey

(

)

;

       

}

   

}

}

When the code above is compiled and executed, it produces the following result:



75

53.005

2345.7652

True

The following points should be noted when performing type conversion:


Type conversion methods

C# provides a variety of type conversion methods, such as the Convert class, the Parse method, and the TryParse method, which help handle conversions between different data types.

Using the Convert class

The Convert class provides a set of static methods that can convert between various primitive data types.

Example

string

str

=

"123"

;

int

num

=

Convert

.

ToInt32

(

str

)

;

Using the Parse method

The Parse method converts a string to the corresponding numeric type and throws an exception if the conversion fails.

Example

string

str

=

"123.45"

;

double

d

=

double

.

Parse

(

str

)

;

Using the TryParse method

The TryParse method is similar to Parse, but it does not throw an exception; instead, it returns a Boolean value indicating whether the conversion succeeded.

Example

string

str

=

"123.45"

;

double

d

;

bool

success

=

double

.

TryParse

(

str,

out

d

)

;

if

(

success

)

{

    Console

.

WriteLine

(

"Conversion successful: "

d

)

;

}

else

{

    Console

.

WriteLine

(

"Conversion failed"

)

;

}


Custom type conversion

C# also allows you to define custom type conversion operations by defining the implicit or explicit keyword in a type.

Example

using

System

;

public

class

Fahrenheit

{

   

public

double

Degrees

{

get

;

set

;

}

   

public

Fahrenheit

(

double

degrees

)

   

{

        Degrees

=

degrees

;

   

}

   

// implicit conversion from Fahrenheit to double

   

public

static

implicit

operator

double

(

Fahrenheit f

)

   

{

       

return

f

.

Degrees

;

   

}

   

// explicit conversion from double to Fahrenheit

   

public

static

explicit

operator

Fahrenheit

(

double

d

)

   

{

       

return

new

Fahrenheit

(

d

)

;

   

}

}

public

class

Program

{

   

public

static

void

Main

(

)

   

{

        Fahrenheit f

=

new

Fahrenheit

(

98.6

)

;

        Console

.

WriteLine

(

"Fahrenheit object: "

f

.

Degrees

" degrees"

)

;

       

double

temp

=

f

;

// implicit conversion

        Console

.

WriteLine

(

"After implicit conversion to double: "

temp

" degrees"

)

;

        Fahrenheit newF

=

(

Fahrenheit

)

temp

;

// explicit conversion

        Console

.

WriteLine

(

"After explicit conversion back to Fahrenheit: "

newF

.

Degrees

" degrees"

)

;

   

}

}

In the above example, we defined a Fahrenheit class and implemented an implicit conversion from Fahrenheit to double and an explicit conversion from double to Fahrenheit.

The output will be shown as follows:

Fahrenheit object: 98.6 degrees

After implicit conversion to double: 98.6 degrees

After explicit conversion back to Fahrenheit: 98.6 degrees


Summary

In C#, built-in type conversion methods are implemented mainly through the following approaches: implicit conversion, explicit conversion (casting), methods of the Convert class, the Parse method, and the TryParse method. These methods are widely used for conversions between different data types.

The following is a table of C# built-in type conversion methods:

Method category Method Description
Implicit conversion Automatic conversion No explicit specification needed; usually used for safe type conversions, such as from a smaller type to a larger type
Explicit conversion (casting) (type)value Requires explicit specification; usually used in situations that may cause data loss or conversion failure
Convert Class Methods Convert.ToBoolean(value) Convert the specified type to Boolean
Convert.ToByte(value) Convert the specified type to Byte
Convert.ToChar(value) Convert the specified type to Char
Convert.ToDateTime(value) Convert the specified type to DateTime
Convert.ToDecimal(value) Convert the specified type to Decimal
Convert.ToDouble(value) Convert the specified type to Double
Convert.ToInt16(value) Convert the specified type to Int16(short integer)
Convert.ToInt32(value) Convert the specified type to Int32(integer)
Convert.ToInt64(value) Convert the specified type to Int64(long integer)
Convert.ToSByte(value) Convert the specified type to SByte
Convert.ToSingle(value) Convert the specified type to Single(single-precision floating-point)
Convert.ToString(value) Convert the specified type to String
Convert.ToUInt16(value) Convert the specified type to UInt16(unsigned short integer)
Convert.ToUInt32(value) Convert the specified type to UInt32(unsigned integer)
Convert.ToUInt64(value) Convert the specified type to UInt64(unsigned long integer)
Parse Method Boolean.Parse(string) Parse the string as Boolean
Byte.Parse(string) Parse the string as Byte
Char.Parse(string) Parse the string as Char
DateTime.Parse(string) Parse the string as DateTime
Decimal.Parse(string) Parse the string as Decimal
Double.Parse(string) Parse the string as Double
Int16.Parse(string) Parse the string as Int16
Int32.Parse(string) Parse the string as Int32
Int64.Parse(string) Parse the string as Int64
SByte.Parse(string) Parse the string as SByte
Single.Parse(string) Parse the string as Single
UInt16.Parse(string) Parse the string as UInt16
UInt32.Parse(string) Parse the string as UInt32
UInt64.Parse(string) Parse the string as UInt64
TryParse Method Boolean.TryParse(string, out bool) Try to parse the string as Boolean, returning a Boolean value indicating success
Byte.TryParse(string, out byte) Try to parse the string as Byte, returning a Boolean value indicating success
Char.TryParse(string, out char) Try to parse the string as Char, returning a Boolean value indicating success
DateTime.TryParse(string, out DateTime) Try to parse the string as DateTime, returning a Boolean value indicating success
Decimal.TryParse(string, out decimal) Try to parse the string as Decimal, returning a Boolean value indicating success
Double.TryParse(string, out double) Try to parse the string as Double, returning a Boolean value indicating success
Int16.TryParse(string, out short) Try to parse the string as Int16, returning a Boolean value indicating success
Int32.TryParse(string, out int) Try to parse the string as Int32, returning a Boolean value indicating success
Int64.TryParse(string, out long) Try to parse the string as Int64, returning a Boolean value indicating success
SByte.TryParse(string, out sbyte) Try to parse the string as SByte, returning a Boolean value indicating success
Single.TryParse(string, out float) Try to parse the string as Single, returning a Boolean value indicating success
UInt16.TryParse(string, out ushort) Try to parse the string as UInt16, returning a Boolean value indicating success
UInt32.TryParse(string, out uint) Try to parse the string as UInt32, returning a Boolean value indicating success
UInt64.TryParse(string, out ulong) Try to parse the string as UInt64, returning a Boolean value indicating success