C#: How to Check if a string is numeric in C#

How to Check if string is a numeric in C#

In this article, we will learn different ways to check if a string is numeric in c#. We’ll go through typical difficulties and obstacles, as well as best practices for working with string and numeric data types in c#.

Create a Console Application

Assuming you have Visual Studio 2019 or Visual Studio 2022 installed, follow these steps to create a new Console Application.

  • Open the visual studio (IDE).
  • Click on the “Create new project” option.
  • Choose “Console App” from the list of available templates.
  • Click the Next button.
  • The configure a new project, specify the name and location of your project.
  • Click the “Next” button.
  • Then select .Net Core as the runtime and choose the version from the dropdown list at the top.
  • Click the “Create” button

Use TryParse() method to check if a string is a numeric

The TrypParse() method is the simplest way to check if a string is numeric in c#. This method takes in a string and tries to parse it as an integer. If the string is a valid integer, then the method will return true and save the parsed integer value in the out parameter.

string stringvalue = "978912";
int numericvalue;
bool isNumber = int.TryParse(stringvalue, out numericvalue);
if (isNumber == true)
  {
    Console.WriteLine("String contain number");
}
else
{
    Console.WriteLine("String Not contain number");
}

Using Regular Expressions

Regular repression is extremely helpful when checking patterns within a string. And it makes pattern matching more versatile and powerful.

string stringvalue = "901287";
bool isNumber = Regex.IsMatch(stringvalue, @"^\d+$");

if (isNumber == true)
{
    Console.WriteLine("String contain number ");
}
else
{
    Console.WriteLine("String Not contain number");
}

The Regex.IsMatch method to check if the string contains only digits.

See More: Create a Login Form in React TypeScript

Leave a Reply

Your email address will not be published. Required fields are marked *