34

I find myself often needing to use Integer.TryParse to test if a value is an integer. However, when you use TryParse, you have to pass a reference variable to the function, so I find myself always needing to create a blank integer to pass in. Usually it looks something like:

Dim tempInt as Integer
If Integer.TryParse(myInt, tempInt) Then

I find this to be quite cumbersome considering that all I want is a simple True / False response. Is there a better way to approach this? Why isn't there an overloaded function where I can just pass the value I want to test and get a true / false response?

Ryan Smith
  • 8,344
  • 22
  • 76
  • 103
  • 1
    what comes after the "Then" ? Don't you do something with it as an integer? If not, why do you care if it's an integer or not? – Jesse Pepper Jan 07 '09 at 02:52
  • You could write your own which checked to ensure it only held digits and wasn't too big. But that's likely to be slower than a library call. – paxdiablo Jan 07 '09 at 02:55
  • 7
    you can pass the value 0 in the second parameter of the TryParse, you don't need to declare it. – Tom Anderson Jan 07 '09 at 03:02
  • I don't like to do anything after the "Then" I just like to check to make sure things are integer. It makes me feel warm and fuzzy inside. Thanks, I don't know why I didn't think of simply passing 0 or nothing. That will solve the problem. – Ryan Smith Jan 07 '09 at 04:35

7 Answers7

91

No need to declare the integer.

If Integer.TryParse(intToCheck, 0) Then

or

If Integer.TryParse(intToCheck, Nothing) Then

If you have .Net 3.5 ability you can create an extension method for strings.

Public Module MyExtensions

    <System.Runtime.CompilerServices.Extension()> _
    Public Function IsInteger(ByVal value As String) As Boolean
        If String.IsNullOrEmpty(value) Then
            Return False
        Else
            Return Integer.TryParse(value, Nothing)
        End If
    End Function

End Module

And then call like:

If value.IsInteger() Then

Sorry, getting carried away I know, but also you can add this to the MyExtensions class above in .Net 3.5 and not worry unless you need validations.

<System.Runtime.CompilerServices.Extension()> _
Public Function ToInteger(ByVal value As String) As Integer
    If value.IsInteger() Then
        Return Integer.Parse(value)
    Else
        Return 0
    End If
End Function

Then simply use

value.ToInteger()

This will return 0 if it isn't a valid Integer.

Tom Anderson
  • 10,807
  • 3
  • 46
  • 63
9

Since you are using VB.net you can use the IsNumeric Function

If IsNumeric(myInt) Then
    'Do Suff here
End If
a_m0d
  • 12,034
  • 15
  • 57
  • 79
TonyB
  • 3,882
  • 2
  • 25
  • 22
  • 3
    You don't need VB, the "VB runtime" is part of the .NET framework and works just fine from C# – Jonathan Allen Jan 07 '09 at 03:37
  • 11
    IsNumeric is only still in .NET for legacy support. TryParse is the better option. – Justin Clarke May 17 '11 at 13:46
  • 4
    Be careful with IsNumeric, it will return true even for some non Integer values. From the MSDN page "IsNumeric returns True if the data type of Expression is Boolean, Byte, Decimal, Double, Integer, Long, SByte, Short, Single, UInteger, ULong, or UShort, or an Object that contains one of those numeric types. It also returns True if Expression is a Char or String that can be successfully converted to a number." – Dejan Dec 10 '13 at 09:42
5
public static class Util {

    public static Int32? ParseInt32(this string text) {
        Int32 result;
        if(!Int32.TryParse(text, out result))
            return null;
        return result;
    }

    public static bool IsParseInt32(this string text) {
        return text.ParseInt32() != null;
    }

}
yfeldblum
  • 65,165
  • 12
  • 129
  • 169
2

Try this code.

Module IntegerHelpers

  Function IsInteger(ByVal p1 as String) as Boolean
    Dim unused as Integer = 0
    return Integer.TryParse(p1,unused)
  End Function
End Module

The nice part is that since it's declared as a Module level function it can be used without a qualifier. Example Usage

return IsInteger(mInt)
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • @Tom, As the questioner pointed out. TryParse requires a variable. I named it unused to indicate that it will in fact not be used. I could have passed 0 but I wanted it to be clearer it was an unused reference. – JaredPar Jan 07 '09 at 03:07
  • @Tom, that's what you get when you don't use a compiler to verify your solution :(. Fixed – JaredPar Jan 07 '09 at 03:13
1

Why not write an extension method to clean up your code? I haven't written VB.Net for a while, but here is an example in c#:

public static class MyIntExtensionClass
{
  public static bool IsInteger(this string value)
  {
    if(string.IsNullOrEmpty(value))
      return false;

    int dummy;
    return int.TryParse(value, dummy);
  }
}
Jason Jackson
  • 17,016
  • 8
  • 49
  • 74
  • Nice suggestion, should post a vb.net version though, its almost identical except remove the "this" in the param, add the Extension attribute to the method, put it in a module (no need to static functions in a module), and remove the semi-colon and replace brak with end *. – Tom Anderson Jan 07 '09 at 03:12
  • Also, he may not be using .Net 3.5 – Tom Anderson Jan 07 '09 at 03:12
0

A variation would be:

Int32.TryParse(input_string, Globalization.NumberStyles.Integer)
Cerveser
  • 752
  • 8
  • 23
  • The docs for [`Int32.TryParse`](https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse) does not contain this overload `(String, NumberStyles)` but instead has `(String, NumberStyles, IFormatProvider, Int32)`. – Sreenikethan I Apr 08 '20 at 16:38
  • it's the first one in the documentation: TryParse(String, Int32) – Cerveser Apr 09 '20 at 20:06
  • But the usage is incorrect! From the docs: **When this method returns, [result] contains the 32-bit signed integer value equivalent of the number contained in s**. The method which you're referring to (String, Int32) is such that, the parsed value of the String will be STORED IN THE Int32 PARAMETER (because of the `ByRef` keyword)! So it's like saying that "parse the integer, and store it in this variable called `Globalization.NumberStyles.Integer`", which does not make sense. – Sreenikethan I Apr 10 '20 at 11:31
  • OK, if all you need at the end is the `Boolean` value, then I'd suggest replacing `Globalization.NumberStyles.Integer` with `Nothing` because it has no effect anyway. – Sreenikethan I Apr 10 '20 at 11:35
0

J Ambrose Little performed timing tests for IsNumeric checks back in 2003. You may wish to retry the mentioned tests with v2 of the CLR.

icelava
  • 9,787
  • 7
  • 52
  • 74