C# – How to check if string contains only digits

There are plenty of methods to achieve this but even though it’s simple task you need to specify requirements like:

  • are white spaces allowed?
  • how to treat empty string?
  • what’s the maximum length of the string?

In this article I want to describe 3 different ideas how to solve this problem.

Custom function

Let’s say we want to check if string contains digits only, without any white spaces, cannot be empty and also don’t want to introduce any length limitation. We can do it by creating custom function which analyse the text character by character in the loop. It returns false if comes across something different than the range of 0-9.

Having the function created you can use it as below.

For easier usage we can transform it into extension method by making this function static and adding “this” keyword as a prefix to input parameter. We also need to make a class static as it is a requirement of extension methods.

Now the usage is slightly easier as we don’t need to care about object creation. We can notice the results printed on the screen are exactly the same.


If you don’t want to create new function you can use the existing TryParse method, however you need to have in mind the difference in the behavior comparing to previous one. As you can see below, string with leading or trailing white space is still considered to be a “digits only”. The same with the +/- signs which are acceptable here. You also need to remember about the maximum size of int type in C# which is 2147483647. If your potential string is 2147483648 then parse method results with false even if the string has only digits.

Regular Expression

Third option is to use regular expression. It eliminates the requirement of creating separate functions however it’s worst option in terms of performance.


This article presents 3 different approaches to the problem of finding out whether string contains digits only. You need to consider which one is best for you based on the requirements of your application.