How to read inputs as integers in C#

To get integer input from the user in a C# console application, you can use the Console.ReadLine() method to read a string input from the user and then convert it to an integer using the int.Parse() or int.TryParse() method.

Integer Input | C# Console Application

using System; class Program { static void Main(string[] args) { int number; Console.Write("Enter an integer: "); string input = Console.ReadLine(); if (int.TryParse(input, out number)) { Console.WriteLine($"You entered {number}"); } else { Console.WriteLine("Invalid input. Please enter an integer."); } Console.ReadKey(); } }

In the above example, the program prompts the user to enter an integer using Console.Write(). The Console.ReadLine() method reads the input from the user as a string. Then, the int.TryParse() method attempts to convert the input string to an integer. If the conversion is successful, the program outputs the number using Console.WriteLine(). Otherwise, it outputs an error message.

int.TryParse()

Use int.TryParse() instead of int.Parse() to avoid the program crashing in case the user enters a non-integer value. int.TryParse() attempts to parse the string input as an integer, but it returns a boolean value indicating whether the parsing was successful or not, and it outputs the parsed integer as an out parameter.