I know that for reading input by using Convert.To
method,But is there any way to read other than this.
int k = Convert.ToInt16(Console.ReadLine());
I know that for reading input by using Convert.To
method,But is there any way to read other than this.
int k = Convert.ToInt16(Console.ReadLine());
To easiest method to read the input from a console application is Console.ReadLine
. There are possible alternatives but they are more complex and reserved for special cases: See Console.Read or Console.ReadKey.
What is important however is the conversion to an integer number that shouldn't be done using Convert.ToInt32
or Int32.Parse
but with Int32.TryParse
int k = 0;
string input = Console.ReadLine();
if(Int32.TryParse(input, out k))
Console.WriteLine("You have typed a valid integer: " + k);
else
Console.WriteLine("This: " + input + " is not a valid integer");
The reason to use Int32.TryParse
lies in the fact that you can check if the conversion to an integer is possible or not. The other methods instead raises an exception that you should handle complicating the flow of your code.
You can create your own implementation for Console and use it everywhere you want:
public static class MyConsole
{
public static int ReadInt()
{
int k = 0;
string val = Console.ReadLine();
if (Int32.TryParse(val, out k))
Console.WriteLine("You have typed a valid integer: " + k);
else
Console.WriteLine("This: " + val + " is not a valid integer");
return k;
}
public static double ReadDouble()
{
double k = 0;
string val = Console.ReadLine();
if (Double.TryParse(val, out k))
Console.WriteLine("You have typed a valid double: " + k);
else
Console.WriteLine("This: " + val + " is not a valid double");
return k;
}
public static bool ReadBool()
{
bool k = false;
string val = Console.ReadLine();
if (Boolean.TryParse(val, out k))
Console.WriteLine("You have typed a valid bool: " + k);
else
Console.WriteLine("This: " + val + " is not a valid bool");
return k;
}
}
class Program
{
static void Main(string[] args)
{
int s = MyConsole.ReadInt();
}
}
you can use int.TryParse
see example
var item = Console.ReadLine();
int input;
if (int.TryParse(item, out input))
{
// here you got item as int in input variable.
// do your stuff.
Console.WriteLine("OK");
}
else
Console.WriteLine("Entered value is invalid");
Console.ReadKey();
Here is an alternative and best method that you can follow:
int k;
if (int.TryParse(Console.ReadLine(), out k))
{
//Do your stuff here
}
else
{
Console.WriteLine("Invalid input");
}
There are 3 types of integers:
1.) Short Integer : 16bit number (-32768 to 32767). In c# you can declare a short integer variable as short
or Int16
.
2.) "Normal" Integer: 32bit number (-2147483648 to 2147483647). Declare a integer with the keywords int
or Int32
.
3.) Long Integer: 64bit number (-9223372036854775808 to 9223372036854775807). Declare a long integer with long
or Int64
.
The difference is the range of numbers you can use.
You can convert them by using Convert.To
, Parse
or TryParse
.