We use parsing to change text input into numbers so the computer can do math with it.
0
0
Parsing input to numeric types in C Sharp (C#)
Introduction
When you get numbers typed by a user as text and want to add or multiply them.
When reading numbers from a file or website that come as text.
When you want to check if a text can be a number before using it.
When converting text boxes input in a program into numbers for calculations.
Syntax
C Sharp (C#)
int number = int.Parse(stringInput); double value = double.Parse(stringInput); bool success = int.TryParse(stringInput, out int result);
Parse converts text to a number but throws an error if it fails.
TryParse tries to convert and returns true or false without error.
Examples
This converts the text "25" into the number 25.
C Sharp (C#)
int age = int.Parse("25");
This converts the text "19.99" into the number 19.99.
C Sharp (C#)
double price = double.Parse("19.99");
This safely tries to convert userInput to a number without crashing if it fails.
C Sharp (C#)
if (int.TryParse(userInput, out int number)) { // use number here } else { // handle invalid input }
Sample Program
This program asks the user to type a number. It tries to convert the typed text to a number safely. If it works, it shows the number and adds 10 to it. If not, it tells the user the input was invalid.
C Sharp (C#)
using System; class Program { static void Main() { Console.Write("Enter a number: "); string input = Console.ReadLine(); if (int.TryParse(input, out int number)) { Console.WriteLine($"You entered the number {number}."); Console.WriteLine($"Number plus 10 is {number + 10}."); } else { Console.WriteLine("That is not a valid number."); } } }
OutputSuccess
Important Notes
Always use TryParse when reading user input to avoid program crashes.
Remember that Parse will throw an exception if the input is not a valid number.
Parsing respects the current culture for decimal points (e.g., dot or comma).
Summary
Parsing changes text into numbers so you can do math.
Use Parse when you are sure the text is a number.
Use TryParse to safely check and convert user input.