How to validate whether a string is a number in C#?


A string having number can be validated using int.TryParse or int.Parse.

Int.Parse throws an exception if it cannot parse the string to an integer, whereas Int.TryParse returns a bool indicating whether it succeeded. Also, Int.TryParse has an out parameter which has the value of the parsed string.

Example

 Live Demo

using System;
namespace DemoApplication {
   class Program {
      static void Main(string[] args) {
         string numberString = "123";
         int number = 0;
         if(int.TryParse(numberString, out number)) {
            Console.WriteLine($"Try Parse Interger Number: {number}");
         }
         Console.WriteLine($"Parse Interger Number: {int.Parse(numberString)}");
         Console.ReadLine();
      }
   }
}

Output

The output of the code is

Try Parse Interger Number: 123
Parse Interger Number: 123

In the above example since int.Tryparse returns a boolean value along with the parsed string in the out parameter, the if condition returns true. Also, int.Parse return the integer value as the string contains a proper number.

Example

 Live Demo

using System;
namespace DemoApplication {
   class Program {
      static void Main(string[] args) {
         string numberString = "A123";
         int number = 0;
         if(int.TryParse(numberString, out number)) {
            Console.WriteLine($"Try Parse Interger Number: {number}");
         }
         elsem{
            Console.WriteLine($"String doesnot have a proper number");
         }
         Console.ReadLine();
      }
   }
}

Output

The output of the above code is

String doesnot have a proper number

As the string does not have a proper number, the int.Tryparse will return false and the else part of the code is executed. In the same case, int.Parse will throw exception like below.

Example

using System;
namespace DemoApplication {
   class Program {
      static void Main(string[] args) {
         string numberString = "A123";
         Console.WriteLine($"Parse Interger Number: {int.Parse(numberString)}");
         //Exception: Input string was not in correct format.
      }
   }
}

Updated on: 08-Aug-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements