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


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

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 22-Jun-2020

236 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements