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

0 Comments on “C#: How to Check if a string is numeric in C#”

  1. I loved as much as you’ll obtain performed right here. The comic strip is tasteful, your authored material stylish. nonetheless, you command get bought an impatience over that you want be handing over the following. unwell surely come further before once more since precisely the similar nearly a lot regularly inside case you defend this increase.

Leave a Reply

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