You have a string value in your C# program and want to find out if it a numeric value. For example, you have an input field or TextBox, and it contains the string "1234", and you want to validate and test it for a numeric value such as int. Here we look at how you can check number strings, using the exception-free TryParse method on the int type.
First, the string type, which aliases the System.String type in the System namespace, does not define an IsNumber method or similar. However, the int type, which aliases System.Int32, provides the powerful int.TryParse method, which returns true if the input string is a number. Here we see how you can use int.TryParse to test number strings.
=== Program that tests number strings (C#) ===
using System;
class Program
{
static void Main()
{
bool flag1 = IsNumber("1000");
bool flag2 = IsNumber("-11");
bool flag3 = IsNumber("Nope");
Console.WriteLine(flag1);
Console.WriteLine(flag2);
Console.WriteLine(flag3);
}
static bool IsNumber(string value)
{
//
// Return true if this is a number.
//
int number1;
return int.TryParse(value, out number1);
}
}
=== Output of program ===
True
True
FalseNotes on preceding example. The above class Program defines two methods: the Main entry point, and the static IsNumber method. In the Main method, three strings are tested to see if they are numbers. They are specified as the argument to the IsNumber method. The three Boolean flags are then assigned to the result of IsNumber and printed.
Notes on int.TryParse. This method is part of the base class library in the .NET Framework. You can also use double.TryParse, or other related methods on integral type names. It returns true if parsing succeeded (and the string is a number). It returns false if parsing failed (and the string is non-numeric such as "Nope").
Using out parameter. The TryParse method demands an out parameter, which is equivalent to the ref parameter in the Common Language Runtime. The number1 variable here is not used and is just ignored, but it must be sent to int.TryParse anyways. This is not ideal.
Here we looked at a way you can check to see if a string is a numeric value. You can use the powerful and exception-free int.TryParse method with a Boolean method that returns the result of TryParse. Note that you may have to use Trim on your number or remove other punctuation before using the method for best results.