Implicit Conversion
C# performs implicit conversions automatically when no data loss will occur. The compiler handles these conversions without requiring any special syntax.
// Smaller numeric types implicitly convert to larger ones
int smallValue = 42;
long largeValue;
largeValue = smallValue; // int automatically converts to long
// float converts to double
float decimalValue = 3.14f;
double doubleValue = decimalValue; // implicit conversion
// Note: string does not support implicit conversion
string text;
text = smallValue; // Compilation error
Explicit Conversion (Casting)
Using Parse()
The Parse() method converts string values to their corresponding numeric types. This approach works well when the string format is guaranteed to be valid.
string input = "256";
int number = int.Parse(input);
Console.WriteLine(number); // Output: 256
// Edge case: Parse fails with decimal strings
input = "99.9";
// int result = int.Parse(input); // Throws FormatException at runtime
Using Cast Operator
Direct casting truncates decimal values without rounding. This syntax works between numeric types only.
double source = 45.9;
int target = (int)source;
Console.WriteLine(target); // Output: 45
Using Convert Class
The Convert class provides the most flexible conversion utilities in C#. These methods handle edge cases more gracefully than casting.
// Converting numeric types to string
int score = 85;
string output1 = Convert.ToString(score);
string output2 = score.ToString();
string output3 = score + "";
Console.WriteLine(output1); // Output: 85
// Converting string to numeric types
string fraction = "72.5";
double decimalNum = Convert.ToDouble(fraction);
Console.WriteLine(decimalNum); // Output: 72.5
float singlePrecision = Convert.ToSingle(fraction);
Console.WriteLine(singlePrecision); // Output: 72.5
// String to int with Convert
string wholeNumber = "100";
int integerValue = Convert.ToInt32(wholeNumber);
Console.WriteLine(integerValue); // Output: 100
// Converting between numeric types
double largeDecimal = 88.7;
int roundedInt = Convert.ToInt32(largeDecimal);
Console.WriteLine(roundedInt); // Output: 89
largeDecimal = 63.2;
roundedInt = Convert.ToInt32(largeDecimal);
Console.WriteLine(roundedInt); // Output: 63
// Note: rounding occurs when decimal >= 0.5
float smallDecimal = 55.6f;
roundedInt = Convert.ToInt32(smallDecimal);
Console.WriteLine(roundedInt); // Output: 56
Conversion Behavior Summary
| Source Type | Target Type | Method | Rounding Behavior |
|---|---|---|---|
| string | numeric | Parse() or Convert | N/A |
| double | int | (int) cast | Truncate |
| double | int | Convert.ToInt32() | Round (>=0.5 rounds up) |
| float | int | Convert.ToInt32() | Round (>=0.5 rounds up) |
| numeric | string | ToString() or Convert.ToString() | N/A |