Type conversion and parsing
Move values between types safely: implicit and explicit casts, Parse, TryParse and Convert, and what happens when it goes wrong.
"25" (a string) but you need the number 25. Or you have a double but a method needs an int. Converting between types is called type conversion.
Implicit conversion: safe and automatic
int small = 100;long big = small; // int → long: always fitsdouble d = small; // int → double: always fitsConsole.WriteLine(d);100
Explicit conversion (casting): you take responsibility
double price = 9.99;// int whole = price; // error CS0266: cannot implicitly convertint whole = (int)price; // cast: the .99 is cut offConsole.WriteLine(whole);9
From text to numbers
| Method | Bad input | Use it when |
|---|---|---|
int.Parse(s) | FormatException | |
int.TryParse(s, out int n) | false | |
Convert.ToInt32(x) | null gives 0 | object |
Console.Write("Enter your age: ");string? input = Console.ReadLine(); if (int.TryParse(input, out int age)){ Console.WriteLine($"Next year you will be {age + 1}");}else{ Console.WriteLine("That is not a valid number.");}Enter your age: 24 Next year you will be 25
Numbers to text
int count = 42;string a = count.ToString(); // "42"string b = 3.14159.ToString("F2"); // "3.14" (2 decimal places)string c = $"Count: {count}"; // string interpolationConsole.WriteLine(b);3.14
Overflow when casting
int big = 300;byte b = (byte)big; // byte max is 255Console.WriteLine(b); // wraps around: 300 - 256 = 44 checked{ byte c = (byte)big; // throws OverflowException instead}44 Unhandled exception. System.OverflowException
Show a hint
int.TryParse calls joined with && inside one if.
Show the solution
Console.Write("First number: ");string? a = Console.ReadLine();Console.Write("Second number: ");string? b = Console.ReadLine(); if (int.TryParse(a, out int x) && int.TryParse(b, out int y)) Console.WriteLine($"Sum = {x + y}");else Console.WriteLine("Please enter whole numbers only.");First number: 12 Second number: 30 Sum = 42
Remember
Implicit conversions happen automatically when nothing can be lost (int → double). Casts like (int)xare explicit, may lose data, and truncate decimals.Use int.TryParsefor user input;ParseandConvertthrow on bad text.Use ToString()or string interpolation$"..."to turn values into text.