Validating user input with C# - Biz Tech

Validating user input with C#

Listen
using System;

class Program
{
    static void Main(string[] args)
    {
        Console.Write("Enter a number between 1 and 10: ");
        string input = Console.ReadLine();

        if (string.IsNullOrWhiteSpace(input))
        {
            Console.WriteLine("Invalid input.");
            return;
        }

        if (!int.TryParse(input, out int number))
        {
            Console.WriteLine("Invalid input.");
            return;
        }

        if (number < 1 || number > 10)
        {
            Console.WriteLine("Number must be between 1 and 10.");
            return;
        }

        Console.WriteLine("Valid input: " + number);
    }
}
 

This example prompts the user to enter a number between 1 and 10, and then performs the following validation steps:

  1. Check if the input is null or empty using string.IsNullOrWhiteSpace().
  2. Try to parse the input as an integer using int.TryParse().
  3. Check if the number is between 1 and 10. If it is, output the result; otherwise, output an error message.