# VBForums CodeBank > CodeBank - C# >  IsNumeric in C#

## dynamic_sysop

a simple example of implementing the IsNumeric function in to C# i knocked up ...

VB Code:
[color=blue]private bool[/color] [color=black]IsNumeric[/color]([color=blue]object[/color] ValueToCheck)
{
    [color=blue]double[/color] Dummy = [color=blue]new double[/color]();
    [color=blue]string[/color] InputValue = Convert.ToString(ValueToCheck);
     [color=blue]bool[/color] Numeric = [color=blue]double[/color].TryParse( InputValue , System.Globalization.NumberStyles.Any , [color=blue]null[/color] , [color=blue]out[/color] Dummy);
        
    [color=blue]return[/color] Numeric;
}

----------


## Danial

I think there is a built in Function in .net, you should be able to achieve the same with 

Char.IsNumber() method.

----------


## crptcblade

> _Originally posted by Danial_ 
> *I think there is a built in Function in .net, you should be able to achieve the same with 
> 
> Char.IsNumber() method.*


That would only work for single charactersm which means you would have to do a loop for the whole string.  Not to mention checking for decimals and such.

----------


## Danial

> _Originally posted by crptcblade_ 
> *That would only work for single charactersm which means you would have to do a loop for the whole string.  Not to mention checking for decimals and such.*


Yes you are right. I was thinking it cheks the whole string instead of Char. 

My apology  :Blush:

----------


## hellswraith

I hate to be the person that recommends this, but if you need the method, it already exists, so why re-create it.  You can find it here:

MessageBox.Show(Microsoft.VisualBasic.Information.IsNumeric(textBox1.Text));

You just have to reference the Microsoft Visual Basic Runtime.

----------


## ~*McoreD*~

Is it okay to import VB to C#? 

C# executes faster than VB.NET according to http://www.vbconversions.com/topten.aspx. 

If that's true, I would not prefer using IsNumeric from Visual Basic. I would rather use a natice C# method.

----------


## nemaroller

The link you provided that supposedly says C# is faster than vb... lol... take a look at the VB source code they used (see below). They do not explicity declare the variables as ints or doubles, they just leave them as generic objects. Well hell, in code like this that does a loop accessing those properties of the objects, of course it will run slower.


VB Code:
If IsNumeric(Me.txtMaxNbr.Text) = False Then
            MsgBox("Max Nbr must be numeric!", MsgBoxStyle.Exclamation, "Max Nbr Not Numeric")
            Return
        End If
         [b]Dim N, i, j[/b] '<------ WHAT THE HELL
        N = CInt(Me.txtMaxNbr.Text)
        Dim z(N)
        Dim startTime As DateTime = Now
         'initialize array
        For i = 0 To N
            z(i) = 0
        Next
         'mark multiples of i
         For i = 2 To N / 2
            For j = 2 * i To N Step i
                z(j) = 1
            Next
        Next
         'count unmarked numbers, which are primes
        Dim nbr = 0
         For i = 2 To N
            If z(i) = 0 Then
                nbr += 1
            End If
        Next
         Dim ts As New TimeSpan(Now.Ticks - startTime.Ticks)
         Me.lblNbrPrimes.Text = nbr
        Me.lblTime.Text = ts.ToString

----------


## VBGuy

> The link you provided that supposedly says C# is faster than vb... lol... take a look at the VB source code they used (see below). They do not explicity declare the variables as ints or doubles, they just leave them as generic objects. Well hell, in code like this that does a loop accessing those properties of the objects, of course it will run slower.



Also, if you compile the VB code in release mode, I got 1.68 secs for the VB version (even with the lousy variable decs). Compare this to 1.67 for C# and

----------


## Kasracer

To make it cleaner, why not this:


VB Code:
private bool IsNumeric(object ValueToCheck)
        {
            double Dummy = 0;
            return double.TryParse(ValueToCheck.ToString() , System.Globalization.NumberStyles.Any , null , out Dummy);
        }

----------


## robertx

> I hate to be the person that recommends this, but if you need the method, it already exists, so why re-create it.  You can find it here:
> 
> MessageBox.Show(Microsoft.VisualBasic.Information.IsNumeric(textBox1.Text));
> 
> You just have to reference the Microsoft Visual Basic Runtime.


I went looking for another IsNumeric function when I discovered that



```
 
Microsoft.VisualBasic.Information.IsNumeric("010164+")
```

returns True.

The following function gives the desired result:



```
Public Function IsNumeric(ByVal inputString As String) As Boolean
        Dim _isNumber As System.Text.RegularExpressions.Regex = New _
                System.Text.RegularExpressions.Regex("(^[-+]?\d+(,?\d*)*\.?\d*([Ee][-+]\d*)?$)|(^[-+]?\d?(,?\d*)*\.\d+([Ee][-+]\d*)?$)")

        Return _isNumber.Match(inputString).Success
End Function
```

which I found in this thread:

http://www.vbforums.com/showthread.php?t=394507

----------


## Tom Sawyer

The simplest way would be to do something like this:



```

string s = "<whatever>";

try
{
    int i = int.Parse(s)
    ... <Is numeric stuff here>
}
catch
{
    ... <Is not numeric stuff here>
}
```

I'm pretty sure that's how the IsNumeric function is coded in VB as well.  I know that if you have Visual Studio break on all exceptions, the IsDate function throws an error when it finds a non-date, so I assume it's the same for IsNumeric.

----------


## nemaroller

Better way would be attempting to match a compiled Regex ^\d$+$ against the string.

This way you don't get a performance hit by catching an exception.

Or,  tryParse in C# 2.0, which avoids throwing exceptions.

----------


## robertx

> Better way would be attempting to match a compiled Regex ^\d$+$ against the string.
> 
> This way you don't get a performance hit by catching an exception.
> 
> Or,  tryParse in C# 2.0, which avoids throwing exceptions.


That's right. It is considered poor programming practice to capture exceptions as part of the logic when there is some other way of testing first. For example, when dividing two numbers, it is better practice to test the denominator for a zero value than to catch a divide by zero error.

----------

