views:

6483

answers:

6

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?

+1  A: 

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
@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
but your code is incorrect ;) you didn't pass it.
Tom Anderson
-1 will be removed when you fix the code :)
Tom Anderson
@Tom, that's what you get when you don't use a compiler to verify your solution :(. Fixed
JaredPar
+3  A: 

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

If IsNumeric(myInt) Then
    'Do Suff here
End If
TonyB
You don't need VB, the "VB runtime" is part of the .NET framework and works just fine from C#
Jonathan Allen
+19  A: 

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
btw, this doesn't work in c#
Tom Anderson
added in my version with 'Nothing', and +1
Michael Haren
+1, the C# comment is irrelevant to the question since it specifies vb.net.
paxdiablo
Congrats, Tom, you've taken a perfectly good concise answer and turned it into a mushy 500-word essay. :-)
paxdiablo
I would really call it ToIntegerOrDefault(). ToInteger implies to me that it is in fact an integer. Also, it's more efficient to do Integer.TryParse directly in the ToInteger method. Otherwise the Parse will happen twice.
JaredPar
@pax lol, yeah... i just kept going for some reason.
Tom Anderson
+1 Nice answer Tom. By the way, the ToInteger function is declared "As Boolean". You should edit that to say "As Integer".
DoctaJonez
Thanks, just fixed it.
Tom Anderson
A: 

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
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
Also, he may not be using .Net 3.5
Tom Anderson
+1  A: 
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;
    }

}
Justice
Now there's a great use for the nullable!
lc
Wouldn't it be nice if the Framework libraries were reworked from the ground up to take advantage of generics and nullables?
Justice
A: 

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