<style> .reveal-up, .reveal-left, .reveal-right, .reveal-stagger > * { opacity: 1 !important; transform: none !important; } </style>
  1. Learn
  2. C#
  3. Getting started
All lessons in this course

Lesson 4 of 60 12 minBeginner

Type conversion and parsing

Move values between types safely: implicit and explicit casts, Parse, TryParse and Convert, and what happens when it goes wrong.

Values often arrive in the “wrong” type. A user types "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

When no data can be lost, C# converts for you. A small box fits inside a bigger box.

Program.cs
int small = 100;long big = small;        // int → long: always fitsdouble d = small;        // int → double: always fitsConsole.WriteLine(d);
Output
100

Explicit conversion (casting): you take responsibility

When data might be lost, the compiler refuses unless you write a cast: the target type in brackets.

Program.cs
double price = 9.99;// int whole = price;    // error CS0266: cannot implicitly convertint whole = (int)price;  // cast: the .99 is cut offConsole.WriteLine(whole);
Output
9

From text to numbers

Text never converts to a number by casting. Use one of these methods, and see how they behave with good and bad input:

Interactive

Conversion lab

Type what a user might enter. Try 42, 7 , 12.5, abc or 99999999999.

int.Parse("42") 42Works when the text is a valid whole number (spaces around it are allowed).
int.TryParse("42", out int n) true, n = 42Returns true and puts the number in n.
Convert.ToInt32("42") 42Same as int.Parse for text (but returns 0 for null instead of throwing).
MethodBad inputUse it when
int.Parse(s)Throws FormatExceptionYou are sure the text is valid
int.TryParse(s, out int n)Returns falseInput comes from users or files (most of the time)
Convert.ToInt32(x)Throws; null gives 0Converting between many types, including from object
SafeInput.cs
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.");}
Output
Enter your age: 24
Next year you will be 25

Numbers to text

Program.cs
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);
Output
3.14

Overflow when casting

Program.cs
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}
Output
44
Unhandled exception. System.OverflowException
Quick check

What does (int)7.9 give?

Quick check

A user types “abc” where you expect a number. Which call will NOT crash your program?

Practice

Ask the user for two whole numbers and print their sum. If either input is not a valid number, print “Please enter whole numbers only.”

Show a hint

Use two int.TryParse calls joined with && inside one if.

Show the solution
Solution.cs
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.");
Output
First number: 12
Second number: 30
Sum = 42

Remember

  • Implicit conversions happen automatically when nothing can be lost (int → double).
  • Casts like (int)x are explicit, may lose data, and truncate decimals.
  • Use int.TryParse for user input; Parse and Convert throw on bad text.
  • Use ToString() or string interpolation $"..." to turn values into text.
0 of 60 lessons completed