Type Conversion
Often you need to convert data from one type to another. C# provides several ways to do this safely and efficiently.
Implicit Conversion
C# automatically converts types when there's no risk of data loss:
csharp1int myInt = 100;2long myLong = myInt; // int to long (automatic)3double myDouble = myInt; // int to double (automatic)45Console.WriteLine(myLong); // 1006Console.WriteLine(myDouble); // 100
Safe Implicit Conversions
1byte → short → int → long → float → double2 ↓3 decimal
Smaller types can always convert to larger types safely.
Explicit Conversion (Casting)
Use a cast when you want to force a conversion that might lose data:
csharp1double myDouble = 9.78;2int myInt = (int)myDouble; // Cast: double to int34Console.WriteLine(myInt); // 9 (decimal part lost!)
Cast Syntax
csharp1// Casting numeric types2double price = 19.99;3int wholePrice = (int)price; // 1945long bigNumber = 1000000;6int smallerNumber = (int)bigNumber; // Works if value fits78// Be careful with overflow9int large = 300;10byte small = (byte)large; // 44 (overflow! 300 - 256 = 44)
Checked Conversions
Use checked to throw an exception on overflow:
csharp1int large = 300;23// Unchecked (default): silently overflows4byte small1 = (byte)large; // 4456// Checked: throws OverflowException7try8{9 byte small2 = checked((byte)large);10}11catch (OverflowException)12{13 Console.WriteLine("Value too large for byte!");14}
Convert Class
The Convert class provides methods for type conversion:
csharp1// String to numbers2string numStr = "123";3int num1 = Convert.ToInt32(numStr);4double num2 = Convert.ToDouble(numStr);5bool flag = Convert.ToBoolean("true");67// Numbers to string8int value = 42;9string str = Convert.ToString(value);1011// Between numeric types12double d = 9.99;13int i = Convert.ToInt32(d); // 10 (rounds, doesn't truncate!)
Convert vs Cast
csharp1double value = 9.5;23int cast = (int)value; // 9 (truncates)4int convert = Convert.ToInt32(value); // 10 (rounds to nearest)
Parse Methods
Each numeric type has a Parse method for converting strings:
csharp1string numberStr = "42";2string decimalStr = "19.99";3string boolStr = "true";45int number = int.Parse(numberStr);6double price = double.Parse(decimalStr);7bool flag = bool.Parse(boolStr);89Console.WriteLine(number); // 4210Console.WriteLine(price); // 19.9911Console.WriteLine(flag); // True
Parse Throws Exceptions
csharp1// This will throw FormatException!2try3{4 int value = int.Parse("hello");5}6catch (FormatException)7{8 Console.WriteLine("Cannot convert 'hello' to int");9}
TryParse (Safe Parsing)
TryParse returns bool and doesn't throw exceptions:
csharp1string input = "42";2string invalid = "hello";34// TryParse with out parameter5if (int.TryParse(input, out int result))6{7 Console.WriteLine($"Parsed: {result}"); // Parsed: 428}9else10{11 Console.WriteLine("Invalid number");12}1314// Safe parsing of invalid input15if (int.TryParse(invalid, out int value))16{17 Console.WriteLine($"Value: {value}");18}19else20{21 Console.WriteLine("Could not parse"); // This runs22}
TryParse Pattern
csharp1Console.Write("Enter a number: ");2string userInput = Console.ReadLine();34if (double.TryParse(userInput, out double number))5{6 Console.WriteLine($"You entered: {number}");7 Console.WriteLine($"Doubled: {number * 2}");8}9else10{11 Console.WriteLine("That's not a valid number!");12}
ToString Method
Every type can convert to string:
csharp1int number = 42;2double price = 19.99;3bool flag = true;45string s1 = number.ToString(); // "42"6string s2 = price.ToString(); // "19.99"7string s3 = flag.ToString(); // "True"89// Formatted strings10string formatted = price.ToString("C"); // "$19.99"11string fixed2 = price.ToString("F2"); // "19.99"12string percent = 0.85.ToString("P0"); // "85%"
Type Conversion Summary
| Method | Use Case | On Error |
|---|---|---|
| Implicit | Automatic safe conversion | N/A |
(type) cast | Force conversion | May lose data/overflow |
Convert.ToX() | General conversion | Throws exception |
Type.Parse() | String to type | Throws exception |
Type.TryParse() | Safe string parsing | Returns false |
.ToString() | Any type to string | Always works |
Best Practices
csharp1// 1. Use TryParse for user input2if (int.TryParse(userInput, out int value))3{4 // Use value5}67// 2. Use Convert for known-good values8int x = Convert.ToInt32("42");910// 3. Use casting when you understand the consequences11double d = 9.99;12int i = (int)d; // Intentionally truncating1314// 4. Use checked when overflow matters15int big = checked((int)someLongValue);
Summary
In this lesson, you learned:
- Implicit conversion happens automatically for safe type changes
- Use casting
(type)to force conversions that might lose data Convert.ToX()provides robust type conversionParse()converts strings to types but throws on failureTryParse()safely parses strings and returns success/failureToString()converts any type to a string
Next, let's practice with a hands-on workshop!