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
Updated on: 2020-06-22T15:14:57+05:30

366 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements