In C#, the
Console.ReadLine() method is responsible for reading value from the standard read stream. But it returns string so that it will not suitable for reading an integer or other type like float, double, long etc. To do these action, go to Program.cs file of your console application.
Read an integer from console
If we directly use
Convert.ToInt32() method, there is a possibility to generate a runtime format exception that, console input may not contains numeric values and it could not be converted to 32 bit integer which represents value of int type.
- Inside your main method, first of all read from console using
Console.ReadLine() method in a local variable myStr of string type.
Int32.TryParse() method to convert it. Provide the local variable myStr as 1st parameter and a out variable of type int myInt as 2nd parameter which will be accessable in main method.
Console.WriteLine() and provide myInt as the parameter. If you want to do any arithmatic operation on it, add or substruct a value from it. in example bellow, I added with 5.
- Build your application and run it.
static void Main(string args)
string myStr = Console.ReadLine();
Int32.TryParse(myStr, out int myInt);
Console.WriteLine(myInt + 5);