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.
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");
}
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();
}
}
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
orInt16
.2.) "Normal" Integer: 32bit number (-2147483648 to 2147483647). Declare a integer with the keywords
int
orInt32
.3.) Long Integer: 64bit number (-9223372036854775808 to 9223372036854775807). Declare a long integer with
long
orInt64
.The difference is the range of numbers you can use. You can convert them by using
Convert.To
,Parse
orTryParse
.