Open E-School

Male
Friday, February 24, 1984

CSharp (C#) – How to use int.TryParse

Category: Programming Date: Wednesday, March 25, 2015

Goal

Learn how to use int.TryParse to convert a string into integer using C#

What does int.TryParse do?

int.TryParse does two things

  1. It takes a string value and tries to convert it into an integer value.
  2. If it succeeds then it will return true and the integer value
  3. If it fails it will return false and integer value 0

int.TryParse returns two values

You should note the point that the function int.TryParse returns two values. How? By making use of the out parameter concept. The actual return type of int.TryParse is not integer like you see for int.Prase() method. The actual return type for int.TryParse is bool. This is to signal the success or failure of the string to int conversion process.

Then how do we get the converted integer value back?

Int.TryPrase takes two parameters to do the conversion

  1. The string which you want to convert into integer
  2. out parameter in which it will store the converted integer value

Let’s take an example

Look at the code below

using System;    namespace ConsoleApplication1  {      class Program      {          public static void Main(string[] args)          {              int result; // uninitialized int variable              string str = "123";              bool conversionSuccess = int.TryParse(str, out result);                     if (conversionSuccess == true)                  Console.WriteLine("The converted integer value is {0} ", result);              else                  Console.WriteLine("Conversion failed !");            }      }  }

Code explanation

In this code we have declared an int variable named result but we have not initialized it. We will pass a reference to this variable to the int.TryParse method and it will store the converted int value in this variable. Focus on the int.TryParse(str, out result) line of code. On the left side of this line we have a bool variable in which we will store the success or failure for our conversion. The actual converted result will be set into our result variable whose reference we have passed to the int.TryParse method.

In the end we are checking if the conversion was successful or not. If yes then print the converted value. If not then print “conversion failed”.

Rate this article and help us improve

Please Login to rate
Overall ratings: 0 | Rating: out of 5
Previous Article Next Article

Posted By

Open E-School
Member since : 2015-01-09
Total points : 3375

Quick Links

E-Magazines

@

Total Followers
Study Group Created
Study Group Joined
Following Teacher
Following Organization
Blog Articles Added
Questions Asked
Questions Answered
Jobs Posted
Total Members in Group
Questions asked by members
Tasks added in this Group

Please wait..

Ok

Login to Open ESchool OR Create your account    Login   SignUp