Click here to Skip to main content
Click here to Skip to main content

C# Equivalent of VB's IsNumeric()

, 10 Nov 2006
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Chris Fulstow
Technical Lead
United Kingdom United Kingdom
Chris is an ASP.NET MVC tech lead and MCPD with over 12 years' commercial experience producing web-based solutions in a wide range of environments. For the past 8 years he has focused on Microsoft technologies, delivering to major clients in both the public and private sectors.
 
http://chrisfulstow.com/
Follow on   Twitter

Comments and Discussions

 
GeneralMy vote of 5 PinmemberAamir Butt23-Dec-10 20:49 
GeneralMy vote of 5 Pinmembermadushan6-Dec-10 0:35 
GeneralSolution from MS support Pinmemberisponder29-Sep-10 16:23 
GeneralYou can call VB functions in C# ! PinmemberLarsdd2915-Jun-10 19:31 
GeneralA version of IsNumeric PinmemberWes Jones24-Apr-10 8:49 
Generalregexp Pinmembervertex_x15-May-08 19:38 
GeneralIsNumeric() Pinmemberdcdrumm14-Nov-06 23:06 
Generalgood one PinmemberAshish Basran13-Nov-06 3:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140827.1 | Last Updated 10 Nov 2006
Article Copyright 2006 by Chris Fulstow
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid