85

I'm just curious as to whether there is something built into either the C# language or the .NET Framework that tests to see if something is an integer

if (x is an int)
   // Do something

It seems to me that there might be, but I am only a first-year programming student, so I don't know.

na-no.
  • 344
  • 1
  • 3
  • 11
Alex
  • 64,178
  • 48
  • 151
  • 180

10 Answers10

184

Use the int.TryParse method.

string x = "42";
if(int.TryParse(x, out int value))
  // Do something

If it successfully parses it will return true, and the out result will have its value as an integer.

sobelito
  • 1,525
  • 17
  • 13
Brandon
  • 68,708
  • 30
  • 194
  • 223
  • 1
    Do they have a TryParse method for other variable types as well? And is it considered good programming practice to use this method? – Alex Nov 17 '09 at 23:17
  • 3
    Many other .NET primitive types (UInt64, Double, ...) have a `TryParse` method as well. If you have a string, using `TryParse` is usually the best practice to convert it to one of these types. – dtb Nov 17 '09 at 23:23
  • @Alex, try out your intellisense. It can show you every member of every class as you type. – snarf Nov 17 '09 at 23:48
  • I am still getting negative value using this method. Can you tell how should i ignore negative value??@Brandon – Arpit Patel Oct 12 '18 at 03:00
  • @ArpitPatel A negative integer is still a valid integer. If you want to ignore it just do a `< 0` check. – Brandon Oct 12 '18 at 15:39
  • a string having a thousand separators fails – hiFI Jun 09 '23 at 09:22
20

If you just want to check type of passed variable, you could probably use:

    var a = 2;
    if (a is int)
    {
        //is integer
    }
    //or:
    if (a.GetType() == typeof(int))
    {
        //is integer
    }
Piotr Rochala
  • 7,748
  • 2
  • 33
  • 54
  • 1
    Yeah, I guess it really depends on what I initially declare the variable x as. – Alex Nov 17 '09 at 23:12
  • neither of these worked for me. When i looked into it. GetType() was returning int64 but typeof(int) is returning int32. im going to assume the first if does the same thing – Dan Hastings Jun 29 '15 at 15:48
18

I think that I remember looking at a performance comparison between int.TryParse and int.Parse Regex and char.IsNumber and char.IsNumber was fastest. At any rate, whatever the performance, here's one more way to do it.

        bool isNumeric = true;
        foreach (char c in "12345")
        {
            if (!Char.IsNumber(c))
            {
                isNumeric = false;
                break;
            }
        }
Wil P
  • 3,341
  • 1
  • 20
  • 20
  • Scratch the performance comment on TryParse it only applies to int.Parse, Regex and char.IsNumber. The reference I was thinking of came prior to .NET 2.0 when TryParse did not exist yet. – Wil P Nov 18 '09 at 00:02
  • 1
    Here is a decent reference from cp that shows some different ways you can accomplish this. http://www.codeproject.com/KB/cs/csharp-isnumeric.aspx – Wil P Nov 18 '09 at 00:04
  • 6
    an empty string is validated as a number here, you should start with `isNumeric = false` ... – Chtioui Malek Oct 06 '13 at 09:11
  • 1
    A string containing a negative value will not be validated. – Bob Kaufman Mar 28 '16 at 20:07
17

For Wil P solution (see above) you can also use LINQ.

var x = "12345";
var isNumeric = !string.IsNullOrEmpty(x) && x.All(Char.IsDigit);
Georg
  • 1,946
  • 26
  • 18
4

its simple... use this piece of code

bool anyname = your_string_Name.All(char.IsDigit);

it will return true if your string have integer other wise false...

dippas
  • 58,591
  • 15
  • 114
  • 126
Sibghat
  • 49
  • 2
  • 3
    This checks to be sure that all the characters of the string are digits, but doesn't handle negative numbers, numbers with a (no-op) leading `+`, or surrounding whitespace. (The result variable is also confusingly named.) I'm tempted to also ding it for not including e.g. `0.0` or `1,000`(/`1.000` if you're in certain locales), but TryParse doesn't either, so I guess it's no worse. – Nathan Tuggy Dec 24 '14 at 04:36
4

If you only want to check whether it's a string or not, you can place the "out int" keywords directly inside a method call. According to dotnetperls.com website, older versions of C# do not allow this syntax. By doing this, you can reduce the line count of the program.

string x = "text or int";
if (int.TryParse(x, out int output))
{
  // Console.WriteLine(x);
  // x is an int
  // Do something
}
else
{
  // x is not an int
}

If you also want to get the int values, you can write like this.

Method 1

string x = "text or int";
int value = 0;
if(int.TryParse(x, out value))
{
  // x is an int
  // Do something
}
  else
{
  // x is not an int
}

Method 2

string x = "text or int";
int num = Convert.ToInt32(x);
Console.WriteLine(num);

Referece: https://www.dotnetperls.com/parse

DxTx
  • 3,049
  • 3
  • 23
  • 34
2

This function will tell you if your string contains ONLY the characters 0123456789.

private bool IsInt(string sVal)
{
    foreach (char c in sVal)
    {
         int iN = (int)c;
         if ((iN > 57) || (iN < 48))
            return false;
    }
    return true;
}

This is different from int.TryParse() which will tell you if your string COULD BE an integer.
eg. " 123\r\n" will return TRUE from int.TryParse() but FALSE from the above function.

...Just depends on the question you need to answer.

mike
  • 2,149
  • 20
  • 29
1
private bool isNumber(object p_Value)
    {
        try
        {
            if (int.Parse(p_Value.ToString()).GetType().Equals(typeof(int)))
                return true;
            else
                return false;
        }
        catch (Exception ex)
        {
            return false;
        }
    }

Something I wrote a while back. Some good examples above but just my 2 cents worth.

Kwekuq
  • 123
  • 1
  • 1
  • 10
1

Maybe this can be another solution

try
{
    Console.Write("write your number : ");
    Console.WriteLine("Your number is : " + int.Parse(Console.ReadLine()));
}
catch (Exception x)
{
    Console.WriteLine(x.Message);
}
Console.ReadLine();
0

I've been coding for about 2 weeks and created a simple logic to validate an integer has been accepted.

    Console.WriteLine("How many numbers do you want to enter?"); // request a number
    string input = Console.ReadLine(); // set the input as a string variable
    int numberTotal; // declare an int variable

    if (!int.TryParse(input, out numberTotal)) // process if input was an invalid number
    {
        while (numberTotal  < 1) // numberTotal is set to 0 by default if no number is entered
        {
            Console.WriteLine(input + " is an invalid number."); // error message
            int.TryParse(Console.ReadLine(), out numberTotal); // allows the user to input another value
        }

    } // this loop will repeat until numberTotal has an int set to 1 or above

you could also use the above in a FOR loop if you prefer by not declaring an action as the third parameter of the loop, such as

    Console.WriteLine("How many numbers do you want to enter?");
    string input2 = Console.ReadLine();

    if (!int.TryParse(input2, out numberTotal2))
    {
        for (int numberTotal2 = 0; numberTotal2 < 1;)
        {
            Console.WriteLine(input2 + " is an invalid number.");
            int.TryParse(Console.ReadLine(), out numberTotal2);
        }

    }

if you don't want a loop, simply remove the entire loop brace

Shujin
  • 27
  • 5