W_ Kh
W_ Kh

Reputation: 69

Type of input C#

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

Answers (5)

Steve
Steve

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

Gopalakrishnan
Gopalakrishnan

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

CMinor
CMinor

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

sunysen
sunysen

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

Jeroen van Langen
Jeroen van Langen

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

Related Questions