Csharp Type Conversion
In C#, type conversion is the process of converting a value from one data type to another.
Type conversions in C# can be divided into two categories: **implicit type conversion** and **explicit type conversion** (also known as 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 the compiler automatically completing the type conversion when converting a data type of a smaller range to a data type of a larger range. These conversions are C#'s default, safe conversions that do not result in data loss.
For example, from `int` to `long`, from `float` to `double`, etc.
Converting from a smaller integer type to a larger integer type, or from a derived class to a base class. When assigning a `byte` type variable to an `int` type variable, the compiler will automatically convert the `byte` type to `int` type without requiring an explicit conversion.
## 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, this conversion will not result in data loss:
## Example
int intValue =42;
long longValue = intValue;// Implicit conversion, from int to long
### Explicit Type Conversion
Explicit type conversion, i.e., casting, requires the programmer to explicitly specify it in the code.
Explicit conversion refers to the need to use a cast operator to perform an explicit conversion when converting a data type of a larger range to a data type of a smaller range, or when converting one object type to another object type. Casting can cause data loss.
For example, assigning an `int` type variable to a `byte` type variable requires an explicit conversion.
## Example
int i =10;
byte b =(byte)i;// Explicit conversion, requires the use of a cast operator
Casting to an integer type:
## Example
double doubleValue =3.14;
int intValue =(int)doubleValue;// Forced from double to int, data may lose the decimal part
Casting to a floating-point type:
## Example
int intValue =42;
float floatValue =(float)intValue;// Forced 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 demonstrates an explicit type conversion:
## Example
using System;
namespace TypeConversionApplication
{
class ExplicitConversion
{
static void Main(string[] args)
{
double d =5673.74;
int i;
// Force convert double to int
i =(int)d;
Console.WriteLine(i);
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it will produce the following result:
5673
C# provides the following built-in type conversion methods:
| No. | Method & Description |
| --- | --- |
| 1 | **ToBoolean** Converts the type to a Boolean, if possible. |
| 2 | **ToByte** Converts the type to a Byte. |
| 3 | **ToChar** Converts the type to a single Unicode character, if possible. |
| 4 | **ToDateTime** Converts the type (integer or string type) to a DateTime structure. |
| 5 | **ToDecimal** Converts a floating-point or integer type to a Decimal type. |
| 6 | **ToDouble** Converts the type to a double-precision floating-point type. |
| 7 | **ToInt16** Converts the type to a 16-bit integer type. |
| 8 | **ToInt32** Converts the type to a 32-bit integer type. |
| 9 | **ToInt64** Converts the type to a 64-bit integer type. |
| 10 | **ToSbyte** Converts the type to a signed byte type. |
| 11 | **ToSingle** Converts the type to a single-precision floating-point type. |
| 12 | **ToString** Converts the type to a string type. |
| 13 | **ToType** Converts the type to the specified type. |
| 14 | **ToUInt16** Converts the type to a 16-bit unsigned integer type. |
| 15 | **ToUInt32** Converts the type to a 32-bit unsigned integer type. |
| 16 | **ToUInt64** Converts the type to a 64-bit unsigned integer type. |
These methods are all defined in the `System.Convert` class and require the `System` namespace to be included when used. They provide a safe way to perform type conversions because they can handle null values and will throw an exception if the conversion is not possible.
For example, using the `Convert.ToInt32` method to convert a string to an integer:
string str = "123";int number = Convert.ToInt32(str); // Conversion successful, number is 123
If the string is not a valid integer representation, `Convert.ToInt32` will throw a `FormatException`.
The following example converts values of different types to a string type:
## 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 user key press before closing the console window
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it will produce the following result:
7553.0052345.7652True
When performing type conversions, please note the following:
* Implicit conversion can only convert a data type of a smaller range to a data type of a larger range, not the other way around;
* Explicit conversion may result in data loss or reduced precision, requiring a compatibility check of the data types;
* For object type conversions, a compatibility check and a safety check for the type conversion are required.
* * *
## Type Conversion Methods
C# provides various type conversion methods, such as using the `Convert` class, the `Parse` method, and the `TryParse` method. These methods can help handle conversions between different data types.
### Using the Convert Class
The `Convert` class provides a set of static methods that can perform conversions between various basic data types.
## Example
string str ="123";
int num = Convert.ToInt32(str);
### Using the Parse Method
The `Parse` method is used to convert a string to the corresponding numeric type. If the conversion fails, it throws an exception.
## 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 was successful.
## 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 within 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 example above, 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 display 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 primarily implemented through the following ways: implicit conversion, explicit conversion (casting), methods using 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#'s 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 for situations that may cause data loss or conversion failure |
| `Convert` Class Methods | `Convert.ToBoolean(value)` | Converts the specified type to `Boolean` |
| | `Convert.ToByte(value)` | Converts the specified type to `Byte` |
| | `Convert.ToChar(value)` | Converts the specified type to `Char` |
| | `Convert.ToDateTime(value)` | Converts the specified type to `DateTime` |
| | `Convert.ToDecimal(value)` | Converts the specified type to `Decimal` |
| | `Convert.ToDouble(value)` | Converts the specified type to `Double` |
| | `Convert.ToInt16(value)` | Converts the specified type to `Int16` (short integer) |
| | `Convert.ToInt32(value)` | Converts the specified type to `Int32` (integer) |
| | `Convert.ToInt64(value)` | Converts the specified type to `Int64` (long integer) |
| | `Convert.ToSByte(value)` | Converts the specified type to `SByte` |
| | `Convert.ToSingle(value)` | Converts the specified type to `Single` (single-precision floating-point) |
| | `Convert.ToString(value)` | Converts the specified type to `String` |
| | `Convert.ToUInt16(value)` | Converts the specified type to `UInt16` (unsigned short integer) |
| | `Convert.ToUInt32(value)` | Converts the specified type to `UInt32` (unsigned integer) |
| | `Convert.ToUInt64(value)` | Converts the specified type to `UInt64` (unsigned long integer) |
| `Parse` Methods | `Boolean.Parse(string)` | Parses the string to `Boolean` |
| | `Byte.Parse(string)` | Parses the string to `Byte` |
| | `Char.Parse(string)` | Parses the string to `Char` |
| | `DateTime.Parse(string)` | Parses the string to `DateTime` |
| | `Decimal.Parse(string)` | Parses the string to `Decimal` |
| | `Double.Parse(string)` | Parses the string to `Double` |
| | `Int16.Parse(string)` | Parses the string to `Int16` |
| | `Int32.Parse(string)` | Parses the string to `Int32` |
| | `Int64.Parse(string)` | Parses the string to `Int64` |
| | `SByte.Parse(string)` | Parses the string to `SByte` |
| | `Single.Parse(string)` | Parses the string to `Single` |
| | `UInt16.Parse(string)` | Parses the string to `UInt16` |
| | `UInt32.Parse(string)` | Parses the string to `UInt32` |
| | `UInt64.Parse(string)` | Parses the string to `UInt64` |
| `TryParse` Methods | `Boolean.TryParse(string, out bool)` | Attempts to parse the string to `Boolean`, returns a boolean value indicating success |
| | `Byte.TryParse(string, out byte)` | Attempts to parse the string to `Byte`, returns a boolean value indicating success |
| | `Char.TryParse(string, out char)` | Attempts to parse the string to `Char`, returns a boolean value indicating success |
| | `DateTime.TryParse(string, out DateTime)` | Attempts to parse the string to `DateTime`, returns a boolean value indicating success |
| | `Decimal.TryParse(string, out decimal)` | Attempts to parse the string to `Decimal`, returns a boolean value indicating success |
| | `Double.TryParse(string, out double)` | Attempts to parse the string to `Double`, returns a boolean value indicating success |
| | `Int16.TryParse(string, out short)` | Attempts to parse the string to `Int16`, returns a boolean value indicating success |
| | `Int32.TryParse(string, out int)` | Attempts to parse the string to `Int32`, returns a boolean value indicating success |
| | `Int64.TryParse(string, out long)` | Attempts to parse the string to `Int64`, returns a boolean value indicating success |
| | `SByte.TryParse(string, out sbyte)` | Attempts to parse the string to `SByte`, returns a boolean value indicating success |
| | `Single.TryParse(string, out float)` | Attempts to parse the string to `Single`, returns a boolean value indicating success |
| | `UInt16.TryParse(string, out ushort)` | Attempts to parse the string to `UInt16`, returns a boolean value indicating success |
| | `UInt32.TryParse(string, out uint)` | Attempts to parse the string to `UInt32`, returns a boolean value indicating success |
| | `UInt64.TryParse(string, out ulong)` | Attempts to parse the string to `UInt64`, returns a boolean value indicating success |
YouTip