Type conversion is a fundamental concept in C# programming. It allows you to convert values from one data type to another, enabling flexibility and interoperability between different parts of your code.
Implicit conversion occurs automatically when there's no risk of data loss. The compiler handles these conversions without requiring explicit syntax.
int myInt = 10;
long myLong = myInt; // Implicit conversion from int to long
When there's a risk of data loss or when converting between incompatible types, explicit conversion is necessary. This is done using casting syntax.
double myDouble = 3.14;
int myInt = (int)myDouble; // Explicit conversion from double to int
The Convert
class provides methods for converting between various data types. It's particularly useful for string conversions.
string myString = "42";
int myInt = Convert.ToInt32(myString);
Many value types in C# have a Parse
method that converts strings to that type.
string myString = "3.14";
double myDouble = double.Parse(myString);
For safer conversions, use the TryParse
method. It returns a boolean indicating success and outputs the converted value if successful.
string input = "42";
if (int.TryParse(input, out int result))
{
Console.WriteLine($"Conversion successful: {result}");
}
else
{
Console.WriteLine("Conversion failed");
}
C# allows you to define custom conversion operators for your own types. This is useful when working with complex data structures or domain-specific types.
public struct Celsius
{
public double Temperature { get; }
public Celsius(double celsius)
{
Temperature = celsius;
}
public static explicit operator Fahrenheit(Celsius celsius)
{
return new Fahrenheit(celsius.Temperature * 9 / 5 + 32);
}
}
TryParse
methods for user input to handle invalid conversions gracefully.Understanding type conversion is crucial for writing robust C# code. It's closely related to C# Data Types and often used in conjunction with C# Operators. For more advanced scenarios, you might want to explore C# Generics to create more flexible and type-safe code.