views:

228

answers:

3

Hi, I'm just curios 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.

+14  A: 

Use the int.TryParse method.

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

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

Brandon
Oh alright, that's awesome, thanks!
Alex
@dtb, thanks for the clarification.
Brandon
Do they have a TryParse method for other variable types as well? And is it considered good programming practice to use this method?
Alex
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
@Alex, try out your intellisense. It can show you every member of every class as you type.
Snarfblam
+2  A: 

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
    }
rochal
Yeah, I guess it really depends on what I initially declare the variable x as.
Alex
+2  A: 

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
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
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
Thanks for the reference.
Alex