CODEDIGEST
Home Articles CodeDigest Tutorials FAQs
Skip Navigation LinksHome » CodeDigest » Type Conversion using “TryParse()” method   You are not logged in.
Search
 

Technologies
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
Read more..

Read more..

 
Type Conversion using TryParse() method
Type Conversion using TryParse() method
Submitted By Satheesh Babu
On 10/30/2008 7:49:45 AM
Tags: C#,CodeDigest  

Traditionally, we use int.Parse() or Convert.ToInt() method to convert a string to a integer value. With the introduction of .NetFramework 2.0, we have one more method for type conversion called TryParse() method with performance improvements. This method will take the string to be converted as first argument and an out parameter of type int as a second argument and return a Boolean value indicating success or failure.

 

Syntax

Int.TryParse(String,out Int)

bool.TryParse(String,out bool)

 

Usage

string strAge = "25";

        int Age = 0;

        if (!int.TryParse(strAge, out Age))

        {

            //Assign a default value

            Age = 18;

        }

 

When we use int.Parse() method, it will throw an exception for failure which should be catched for assigning a default value. Convert.ToInt() will return a 0 when NULL is passed, else it will again call int.Parse() method for conversion.

 

Hence, it is best to use TryParse() method for type parsing which is optimised for good performance!

 

Refer the following post for performance calculations for all the 3 methods.

Do you have a working code that can be used by anyone? Submit it here. It may help someone in the community!!