using System; class Program { static void Main(string[] args) { Console.Write("Enter the first number: "); string input1 = Console.ReadLine(); Console.Write("Enter the second number: "); string input2 = Console.ReadLine(); if (!int.TryParse(input1, out int number1) || !int.TryParse(input2, out int number2)) { Console.WriteLine("Invalid input."); return; } int result = number1 + number2; Console.WriteLine("The result is " + result + "."); } }This example prompts the user to enter two numbers, performs validation using
int.TryParse()
, and then performs a calculation and outputs the result. The following steps are performed:
- Prompt the user to enter the first number using
Console.Write()
and read the input usingConsole.ReadLine()
.- Prompt the user to enter the second number using
Console.Write()
and read the input usingConsole.ReadLine()
.- Use
int.TryParse()
to attempt to parse the input strings as integers. If parsing fails, output an error message and return from the method using thereturn
keyword.- Perform the calculation using the input numbers.
- Output the result to the console using
Console.WriteLine()
.