Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

C# Equivalent of VB's IsNumeric()

0.00/5 (No votes)
10 Nov 2006 5  
C# alternatives to VB's IsNumeric() function

Introduction

Unlike VB 2005, C# seems to be missing a function for checking whether a string contains a value that can be evaluated as a number. The post will demonstrate some C# alternatives to VB's IsNumeric() function.

Int32.Parse()

First up is the Int32.Parse() method. It's fairly straightforward, you pass it a string parameter and it tries to parse it as an integer. If the string can't be converted to an int, then the method fails and an exception is thrown:

try
{
    int result = int.Parse("123");
    Debug.WriteLine("Valid integer: " + result);
}
catch
{
    Debug.WriteLine("Not a valid integer");
}

Here we're using the int data type which is just a C# synonym for Int32. It's a 32-bit integer, so it will successfully parse any whole number between –2147483648 and 2147483647 inclusive. The Parse() method is also available for other integral types, floating point types and decimals.

This is a good solution, but it's quite verbose and includes the overhead of throwing an exception if the conversion fails.

Int32.TryParse()

The Int32.TryParse() method is a .NET 2.0 refinement of Int32.Parse(). It's more succinct and doesn't throw an exception if parsing fails. Here's how it works:

int result;
if (int.TryParse("123", out result))
{
    Debug.WriteLine("Valid integer: " + result);
}
else
{
    Debug.WriteLine("Not a valid integer");
}

Convert.ToInt32()

The Convert.ToInt32() method is very similar to Int32.Parse() and will throw an exception if the string argument is not a valid Int32 value. The only difference is that Convert.ToInt32() will accept a null argument and evaluate it as zero, whereas Int32.Parse() will throw an ArgumentNullException, i.e.

// throws ArgumentNullExceptionint
result1 = Int32.Parse(null);

// doesn't throw an exception, returns 0
int result2 = Convert.ToInt32(null);

IsNumeric()

That's right, you can call VB's IsNumeric() function directly from C#. First add a reference to the Visual Basic compatibility assembly, Microsoft.VisualBasic.dll, which contains the function's implementation:

Add VB Reference

You can now access any of the methods from the Microsoft.VisualBasic.Information class, including IsNumeric(), like this:

using Microsoft.VisualBasic;
// ......
bool result = Information.IsNumeric("123");

This isn't really a recommended approach because these classes were included in .NET to provide backward compatibility with legacy VB code.

Pattern Matching

Pattern matching using a regular expression is a very flexible solution, and is especially useful if you need to test for very large numbers that might be too big to fit in a variable.

string strToTest = "123";
Regex reNum = new Regex(@"^\d+$");
bool isNumeric = reNum.Match(strToTest).Success;

This pattern will evaluate to true for any non-negative integer. You could adapt the regular expression to include any number format you want, such as negative, decimal or even complex numbers.

Char.IsNumber() and Char.IsDigit()

Finally, I'll just mention two methods of the char class, Char.IsNumber() and Char.IsDigit(). These can be used to check whether a single character is a number, e.g.

bool isNumeric = Char.IsNumber('5');  // true

The differences between these two methods are quite subtle, so read the documentation carefully to make sure you're using the right one.

Summary

To borrow a phrase from Perl, There's More Than One Way To Do It (TIMTOWTDI). Wrap any of these techniques in a method and you've got your very own C# IsNumeric() function.

Quick Warning

One final word of warning, be careful with code like this:

string str = "\x1811\x1812\x1813";
Regex reNum = new Regex(@"^\d+$");
if (reNum.Match(str).Success) // evaluates to true
{
    int i = int.Parse(str); // throws FormatException
}

Your regular expression \d digit character will match any Unicode digit, even if, as shown here, it's Mongolian. The Int32.Parse() method isn't quite as pragmatic and will throw a FormatException.

History

  • 10th November, 2006: Initial post

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here