C# int.Parse Vs int.TryParse Method


Convert a string representation of number to an integer,using the int.TryParse and intParse method in C#.

If the string cannot be converted, then the int.TryParse method returns false i.e. a Boolean value, whereas int.Parse returns an exception.

Let us see an example of int.Parse method −

Example

 Live Demo

using System.IO;
using System;
class Program {
   static void Main() {
      int res;
      string myStr = "120";
      res = int.Parse(myStr);
      Console.WriteLine("String is a numeric representation: "+res);
   }
}

Output

String is a numeric representation: 120

Let us see an example of int.TryParse method.

Example

 Live Demo

using System.IO;
using System;
class Program {
   static void Main() {
      bool res;
      int a;
      string myStr = "120";
      res = int.TryParse(myStr, out a);
      Console.WriteLine("String is a numeric representation: "+res);
   }
}

Output

String is a numeric representation: True

Updated on: 22-Jun-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements