testing if a string can be cast as a integer in VB.NET

Booji Boy picture Booji Boy · Nov 3, 2009 · Viewed 17.5k times · Source

Is there a better way of testing if a string can be converted to an integer other than something like the following?

Public Function IsInt(ByVal value As Object) As Boolean
    Try
        Dim temp As Integer = CInt(value)
        Return True
    Catch ex As Exception
        Return False
    End Try
End Function

by "better" I mean less verbose and/or w/o an exception.

TryParse would be the way to go, but I'm using the compact framework 2.0 and tryparse doesn't seem to be implemented....

Thanks anyways.

It seems that MarkJ is correct and the above seems to be functionally the same as IsNumeric, so I suppose that's my answer. I don't know why I thought CInt was more strict than IsNumeric. I guess it's better to test using CInt verses IsNumeric since that's the function I'm using to do the conversion?

Answer

Geoff Appleford picture Geoff Appleford · Nov 3, 2009

You can use the built in IsNumeric Function

Dim CanConvert as Boolean = IsNumeric(value)

http://msdn.microsoft.com/en-us/library/6cd3f6w1(VS.71).aspx