Parse
Part of the Fundamentals section of Coddy's C# journey — lesson 34 of 69.
In C#, when you read input from the console using Console.ReadLine(), it always returns a string. To use this input as a number or another data type, you need to convert it. The Parse method is commonly used for this purpose.
Parse is a method that converts a string to another data type. It throws an exception if the conversion fails.
Here's an example:
string numberString = "42";
int number = int.Parse(numberString); // Converts "42" to the integer 42If the string cannot be parsed, Parse will throw a FormatException. For example:
string invalidNumberString = "abc";
int number = int.Parse(invalidNumberString); // Throws FormatExceptionOther common types:
| Data Type | Parse Method | Example |
|---|---|---|
int | int.Parse() | int number = int.Parse("42"); |
double | double.Parse() | double number = double.Parse("42.5"); |
float | float.Parse() | float number = float.Parse("42.5"); |
bool | bool.Parse() | bool isTrue = bool.Parse("true"); |
Challenge
BeginnerWrite a C# program that reads two numbers from the console as strings, converts them to integers using Parse, and then prints the sum of the numbers. The program should do the following:
- Read the first number as a string.
- Read the second number as a string.
- Use
int.Parse()to convert the numbers to integers. - Print the sum of the two numbers.
Cheat sheet
Use Parse methods to convert strings to other data types:
string numberString = "42";
int number = int.Parse(numberString); // Converts "42" to integer 42Parse throws a FormatException if the conversion fails:
string invalidNumberString = "abc";
int number = int.Parse(invalidNumberString); // Throws FormatExceptionCommon Parse methods:
| Data Type | Parse Method | Example |
|---|---|---|
int |
int.Parse() |
int number = int.Parse("42"); |
double |
double.Parse() |
double number = double.Parse("42.5"); |
float |
float.Parse() |
float number = float.Parse("42.5"); |
bool |
bool.Parse() |
bool isTrue = bool.Parse("true"); |
Try it yourself
using System;
public class Program {
public static void Main(string[] args) {
string firstNumberString = Console.ReadLine();
string secondNumberString = Console.ReadLine();
// Use Parse to convert the numbers
// Print the sum of the numbers
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic Shortcuts5Operators Part 2
Comparison OperatorsLogical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3