This post will discuss how to identify if a given string is numeric or not in C#.

There are several methods to check if the given string is numeric in C#:

1. Using Regular Expression

The idea is to use the regular expression ^[0-9]+$ or ^\d+$, which checks the string for numeric characters. This can be implemented using the Regex.IsMatch() method, which tells whether the string matches the given regular expression. To allow empty strings, just replace + with *.

Note that regex [0-9] is not equivalent to \d. [0-9] matches with a character in the range 0 through 9, while \d matches ASCII 0-9 and other digit characters like Eastern Arabic numerals ٠١٢٣٤٥٦٧٨٩.

Download  Run Code

 
If the regular expression is frequently called, compile the regular expression first for faster execution in subsequent calls.

Download  Run Code

2. Using Enumerable.All() method

LINQ’s Enumerable.All() method returns true when all elements of a sequence satisfy a condition. To test for numeric characters, pass Char.IsDigit to the Enumerable.All() method.

Download  Run Code

 
Note that the IsDigit() method does not strictly check for a character in the range 0 through 9. It allows a few characters such as Thai numerals ๐ ๑ ๒ ๓ ๔ ๕ ๖ ๗ ๘ ๙. We can use the following code to strictly check for ASCII digits:

Download  Run Code

3. Using Enumerable.Any() method

LINQ’s Enumerable.Any() method returns true when any element of a sequence satisfy a condition. To test for numeric characters, escape the range 0 to 9. The following code example shows how to implement this.

Download  Run Code

4. Using Int.TryParse() method

To determine whether a string is numeric, convert it into its 32-bit signed integer equivalent using the Int32.TryParse() method. Following is a simple example demonstrating usage of this method:

Download  Run Code

5. Using foreach loop

A naive solution is to iterate over characters of the string and check each character to be numeric. This is demonstrated below:

Download  Run Code

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