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 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");
}
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:
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.