Menu
Coddy logo textTech

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 42

If the string cannot be parsed, Parse will throw a FormatException. For example:

string invalidNumberString = "abc";
int number = int.Parse(invalidNumberString); // Throws FormatException

Other common types:
 

Data TypeParse MethodExample
intint.Parse()int number = int.Parse("42");
doubledouble.Parse()double number = double.Parse("42.5");
floatfloat.Parse()float number = float.Parse("42.5");
boolbool.Parse()bool isTrue = bool.Parse("true");
challenge icon

Challenge

Beginner

Write 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:

  1. Read the first number as a string.
  2. Read the second number as a string.
  3. Use int.Parse() to convert the numbers to integers.
  4. 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 42

Parse throws a FormatException if the conversion fails:

string invalidNumberString = "abc";
int number = int.Parse(invalidNumberString); // Throws FormatException

Common 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
        
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals