Get a number from the console

Jump to: navigation, search

This C# code snippet obtains a string from the console and converts it to a number.

using System;
...
 
try
{
   int number = Convert.ToInt32 (Console.ReadLine());
   Console.WriteLine ("Number: " + number);
}
catch (FormatException e)
{
   Console.WriteLine (e.Message);
}
 
// or ...
 
try
{
   int number = Int32.Parse (Console.ReadLine());
   Console.WriteLine ("Number: " + number);
}
catch (ArgumentNullException e)
{
   Console.WriteLine (e.Message);
}
C# Online.NET