Sabari M Sabari M
Updated date Feb 22, 2021
In this code snippet, we will see how to identify if a string is numeric or not in C#. This code snippet helps for the fresh or experienced C# developers.

In this code snippet, we will see how to identify if a string is numeric or not in C#. This code snippet helps for the fresh or experienced C# developers.

Using Regular Expression:

Example 1: Give input is numeric

using System;
using System.Text.RegularExpressions;

namespace SampleApp
{
    class FindNumeric
    {
        public static void Main()
        {
            var regex = new Regex(@"^\d+$");
            var str = "1000";

            if (regex.IsMatch(str))
            {
                Console.WriteLine("This is a numeric value");
            }
            else
            {
                Console.WriteLine("This is not a numeric value");
            }
            Console.ReadKey();
        }
    }
}

Output: 

This is a numeric value

Example 2: Give input is non-numeric

using System;
using System.Text.RegularExpressions;

namespace SampleApp
{
    class FindNumeric
    {
        public static void Main()
        {
            var regex = new Regex(@"^\d+$");
            var str = "TechieClues";

            if (regex.IsMatch(str))
            {
                Console.WriteLine("This is a numeric value");
            }
            else
            {
                Console.WriteLine("This is not a numeric value");
            }
            Console.ReadKey();
        }
    }
}

Output:

This is not a numeric value

Using Enumerable.All Method

Example:

using System;
using System.Linq;

namespace SampleApp
{
    class FindNumeric
    {
        public static void Main()
        {   
            var str = "1000";
            if (str.All(char.IsDigit))
            {
                Console.WriteLine("This is a numeric value");
            }
            else
            {
                Console.WriteLine("This is a not a numeric value");
            }
                        
            var str1 = "TechieClues";
            if (str1.All(char.IsDigit))
            {
                Console.WriteLine("This is a numeric value");
            }
            else
            {
                Console.WriteLine("This is not a numeric value");
            }

            Console.ReadKey();
        }
    }
}

Output:

This is a numeric value
This is not a numeric value

 

ABOUT THE AUTHOR

Sabari M
Sabari M
Software Professional, India

IT professional with 14+ years of experience in Microsoft Technologies with a strong base in Microsoft .NET (C#.Net, ASP.Net MVC, ASP.NET WEB API, Webservices,...Read More

https://www.techieclues.com/profile/alagu-mano-sabari-m

Comments (0)

There are no comments. Be the first to comment!!!