This article illustrates the different techniques to check if a string is a number in C#.

1. Using TryParse() method

You can use the TryParse() method to identify if a string is a number. It works by converting the specified string to equivalent signed integer representation and returns true if the conversion succeeded; otherwise, false. Here’s what the code would look like:

Download  Run Code

 
Note that the TryParse() method takes an Out parameter, which stores the integer value if the conversion was a success. This can be shortened to below if the Out parameter is not needed.

Download  Run Code

 
Note that the Out parameter is declared and initialized in separate statements. Starting with C# 7, we can in-line declare and initialize the Out parameter.

Download  Run Code

2. Using Char.IsDigit() method

The Char.IsDigit() method returns a boolean value indicating if the specified character is a digit. The following code example demonstrates the usage of the Char.IsDigit() method with the Enumerable.All() method to determine if a string is a number.

Download  Run Code

3. Using Regex.IsMatch() method

Finally, you can use the regular expression to check if a string is numeric. This can be done using the Regex.IsMatch() method, which determines if the specified string matches with the supplied regex. This is demonstrated below. Note that ^ matches with the beginning of the string and $ match with its end.

Download  Run Code

That’s all about checking if a string is a number in C#.