How to validate a string for a numeric representation using TryParse in C#

ProgrammingServer Side ProgrammingCsharp

The following is our string −

string myStr = "5";

To check whether the above is a string with numeric representation, use TryParse and out.

int.TryParse(myStr, out a);

Here is the complete code.

Example

 Live Demo

using System.IO;
using System;
class Program {
   static void Main() {
      bool res;
      int a;
      string myStr = "5";
      // checking for valid string representation of a number
      res = int.TryParse(myStr, out a);
      Console.WriteLine(res);
   }
}

Output

True
raja
Published on 11-Sep-2018 08:14:25
Advertisements