Reputation: 69
Actually I'm trying to write small program that read input from user to decide whether is it integer
or not.
object x=Console.ReadLine();
check(x);
static void check(object x)
{
if (x.GetType() == typeof(int))
Console.WriteLine("int");
else
Console.WriteLine("not int");
}
Upvotes: 3
Views: 3858
Reputation: 216313
Just use Int.TryParse as in this example
int result;
string x = Console.ReadLine();
if(int.TryParse(x, out result))
Console.WriteLine("int");
else
Console.WriteLine("not int");
The method accepts the input string and an integer variable. If the string can be converted to an integer number, then the integer variable is initialized with the converted string and the method returns true. Otherwise the method returns false and the integer variable passed will be set to zero.
As a side note. Console.ReadLine returns a string
Upvotes: 6
Reputation: 517
Console.ReadLine()
Will Always Return String . So you can Try Int.TryParse()
To Check the type. Check the bellow Example
int output;
string x = Console.ReadLine();
if(int.TryParse(x, out output)
Console.WriteLine("int");
else
Console.WriteLine("not int");
hope This may helpful for you.
Upvotes: 0
Reputation: 427
Try this
int isInteger;
Console.WriteLine("Input Characters: ");
string x = Console.ReadLine();
if(int.TryParse(x, out isInteger)
Console.WriteLine("int");
else
Console.WriteLine("not int");
Upvotes: 1
Reputation: 2351
try
static void check()
{ int result
string x = Console.ReadLine();
if(int.TryParse(x, out result)
Console.WriteLine("int");
else
Console.WriteLine("not int");
}
Upvotes: 4
Reputation: 22073
You can use this:
string x = Console.ReadLine();
int i;
if(int.TryParse(x, out i))
Console.WriteLine("int");
else
Console.WriteLine("not int");
If the TryParse()
returns true
, the parsed value is stored in i
Upvotes: 12