IsNumeric Best Practices

Needing to find out what the best why to implement the IsNumeric function in C# is, I went on a brief tour of the Internet today.  My result is a very informative article by J. Ambrose Little that benchmarks six (count 'em, six) different techniques.  The result is a virtual tie between an incremental character technique (use the Char.IsNumeric method on each character in a string), the Double.TryParse and VisualBasic.IsNumeric.  Useful information to keep in mind in the future.

Comments

  • bruce October 31, 2003 10:59 AM

    Bruce...

    We had a similar situation coding in VB .net. We didn't want to import Microsoft.VisualBasic so we added this method to our framework. Mind you it's only for integers.

    Public Function IsInteger(ByVal value As String) As Boolean
    Dim result As Boolean = True
    Try
    System.Int32.Parse(value)
    Catch ex As Exception
    result = False
    End Try
    Return result
    End Function

    Should we have done it differently?

    Dave

  • bruce October 31, 2003 2:35 PM

    I'm afraid that the answer is 'yes'. Actually, the true answer depends on the situation. The Parse method is faster than TryParse in those situations where the value is a number. However, the cost of throwing and catching the exception means that invalid values are much slower. So the 'best' solution depends on the liklihood of getting invalid input.

    Interestingly, if you decompile the IsNumeric function in the Microsoft.VisualBasic namespace, you find at its heart...a call to TryParse. That probably says more about the best choice than anything else

Leave a Comment

(required) 
(optional)
(required) 

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS