10 minlesson

Type Conversion

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:

csharp
1int myInt = 100;
2long myLong = myInt; // int to long (automatic)
3double myDouble = myInt; // int to double (automatic)
4
5Console.WriteLine(myLong); // 100
6Console.WriteLine(myDouble); // 100

Safe Implicit Conversions

1byte → short → int → long → float → double
2
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:

csharp
1double myDouble = 9.78;
2int myInt = (int)myDouble; // Cast: double to int
3
4Console.WriteLine(myInt); // 9 (decimal part lost!)

Cast Syntax

csharp
1// Casting numeric types
2double price = 19.99;
3int wholePrice = (int)price; // 19
4
5long bigNumber = 1000000;
6int smallerNumber = (int)bigNumber; // Works if value fits
7
8// Be careful with overflow
9int large = 300;
10byte small = (byte)large; // 44 (overflow! 300 - 256 = 44)

Checked Conversions

Use checked to throw an exception on overflow:

csharp
1int large = 300;
2
3// Unchecked (default): silently overflows
4byte small1 = (byte)large; // 44
5
6// Checked: throws OverflowException
7try
8{
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:

csharp
1// String to numbers
2string numStr = "123";
3int num1 = Convert.ToInt32(numStr);
4double num2 = Convert.ToDouble(numStr);
5bool flag = Convert.ToBoolean("true");
6
7// Numbers to string
8int value = 42;
9string str = Convert.ToString(value);
10
11// Between numeric types
12double d = 9.99;
13int i = Convert.ToInt32(d); // 10 (rounds, doesn't truncate!)

Convert vs Cast

csharp
1double value = 9.5;
2
3int 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:

csharp
1string numberStr = "42";
2string decimalStr = "19.99";
3string boolStr = "true";
4
5int number = int.Parse(numberStr);
6double price = double.Parse(decimalStr);
7bool flag = bool.Parse(boolStr);
8
9Console.WriteLine(number); // 42
10Console.WriteLine(price); // 19.99
11Console.WriteLine(flag); // True

Parse Throws Exceptions

csharp
1// This will throw FormatException!
2try
3{
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:

csharp
1string input = "42";
2string invalid = "hello";
3
4// TryParse with out parameter
5if (int.TryParse(input, out int result))
6{
7 Console.WriteLine($"Parsed: {result}"); // Parsed: 42
8}
9else
10{
11 Console.WriteLine("Invalid number");
12}
13
14// Safe parsing of invalid input
15if (int.TryParse(invalid, out int value))
16{
17 Console.WriteLine($"Value: {value}");
18}
19else
20{
21 Console.WriteLine("Could not parse"); // This runs
22}

TryParse Pattern

csharp
1Console.Write("Enter a number: ");
2string userInput = Console.ReadLine();
3
4if (double.TryParse(userInput, out double number))
5{
6 Console.WriteLine($"You entered: {number}");
7 Console.WriteLine($"Doubled: {number * 2}");
8}
9else
10{
11 Console.WriteLine("That's not a valid number!");
12}

ToString Method

Every type can convert to string:

csharp
1int number = 42;
2double price = 19.99;
3bool flag = true;
4
5string s1 = number.ToString(); // "42"
6string s2 = price.ToString(); // "19.99"
7string s3 = flag.ToString(); // "True"
8
9// Formatted strings
10string formatted = price.ToString("C"); // "$19.99"
11string fixed2 = price.ToString("F2"); // "19.99"
12string percent = 0.85.ToString("P0"); // "85%"

Type Conversion Summary

MethodUse CaseOn Error
ImplicitAutomatic safe conversionN/A
(type) castForce conversionMay lose data/overflow
Convert.ToX()General conversionThrows exception
Type.Parse()String to typeThrows exception
Type.TryParse()Safe string parsingReturns false
.ToString()Any type to stringAlways works

Best Practices

csharp
1// 1. Use TryParse for user input
2if (int.TryParse(userInput, out int value))
3{
4 // Use value
5}
6
7// 2. Use Convert for known-good values
8int x = Convert.ToInt32("42");
9
10// 3. Use casting when you understand the consequences
11double d = 9.99;
12int i = (int)d; // Intentionally truncating
13
14// 4. Use checked when overflow matters
15int 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 conversion
  • Parse() converts strings to types but throws on failure
  • TryParse() safely parses strings and returns success/failure
  • ToString() converts any type to a string

Next, let's practice with a hands-on workshop!