OneBite.Dev - Coding blog in a bite size

Check If A String Contains Only Numbers In C#

Code snippet for how to Check If A String Contains Only Numbers In C# with sample and detail explanation

Handling strings is an integral part of every programming language, including C#. One common task is to verify if a string contains only numeric characters. In C#, there are several ways to accomplish this.

Check If A String Contains Only Numbers In C#

C# provides various methods to check if a string contains only numbers. You can utilize the All method from the System.Linq namespace in combination with the char.IsDigit method to get a boolean result on whether all characters in the string are numeric or not. Here’s a sample code snippet:

using System;
using System.Linq;

class Program
{
    static void Main()
    {
        string input = "123456";
        bool isNumeric = input.All(char.IsDigit);
        Console.WriteLine(isNumeric);
    }
}

If the string “input” contains only numbers, the output will be ‘True’. If the string contains any non-numeric character, the output will be ‘False’.

Code Explanation for Checking If A String Contains Only Numbers In C#

Let’s break down the above code to understand each step.

Step 1: If you haven’t already, make sure you have the System.Linq namespace in your using directives. This namespace provides methods for querying objects, including the All method we will use.

using System;
using System.Linq;

Step 2: Declare the string that you would like to check.

string input = "123456";

Step 3: Use the All method in conjunction with the char.IsDigit function to check if all the characters in your string are digits.

bool isNumeric = input.All(char.IsDigit);

The All method checks whether all elements of a sequence satisfy a condition. In this case, it checks all characters in our array (formed from the string ‘input’) are digits. The char.IsDigit method determines whether a char value is a digit.

Step 4: The Console.WriteLine(isNumeric); line prints the result of our check (either ‘True’ or ‘False’) to the console.

The beauty of this approach is its simplicity and efficiency. You can easily extend this method for various string processing strategies in C#.

c-sharp