User Id :    Password :      New Member   Forgot Password  
 
Using TryParse Methods in C#
Description TryParse methods which is provided by the .net framewok is one of the important method when you are converting string data into perticular primary datatype and wants to verify that it is convertable in given type or not.   No. of Views     1221
  Rating     0
Author Pranay Rana   Posted On     12 Apr 2012
Tags C#,.NET Frameworks    

Sample Code   Download Code

TryParse methods which is provided by the .net framewok is one of the important method when you are converting string data into perticular primary datatype and wants to verify that it is convertable in given type or not.

Syntax

boolean datatype.TryParse(stringvariable, out datatypevariable)

   

As in syntax TryPrase method of the datatype try to convert stringvalue in the given datatype if it succeeds than returns true and assign value to datatypevariable otherwise return false.

Where to Use :
- Avoid runtime error of converting explicite data type.

object s = "5b";
int a = (int)s;

   

- To replace Parse Method code which is throws runtime exception.

string s = "5b";
int a = int.Parse(s);

   

- When you want to validate data which you are reading from your textbox.

Example
I am going to discuss about the case where I found it useful and how it's helpful to you in your project.

Recently I was working on project which is reading data from the excel file which contains employee details and converting that excel in the DataTable format.

 

 

Now the requirement to displaying the employee by employeeid and those employeeids are not valid I have to display them in last.

So the solution to this is make use of Linq with the int.Typarse Method.
   

int myInt;
var Employee = (from row in dtEmployee.AsEnumerable()
         orderby  (int.TryParse(row ["Employeeid"]).ToString(), out myInt) ?  myInt: 0 )
         select row ).ToList<datarow>();



So the above method return the employeeid in asending order and display the row which are not integer at last.
As you can see TryPrase method of int in Linq query return employeeid if its integer and 0 if the employeeid is not integer.

 

About Author

About Author Hey, I am Pranay Rana, working as a Senior Software engineer. Web development in Asp.Net with C# and MS sql server are the experience tools that I have had for the past 5 years now.
For me def. of programming is : Programming is something that you do once and that get used by multiple for many years
You can visit me on my blog - http://pranayamr.blogspot.com/
Pranay Rana
No Photo
 
Country India
Company GMind Solutions
Home Page http://pranayamr.blogspot.com/

Rate this article

Rating options from poor, fair, good, very good to excelent.  
 

Comments

   
Write your comment here.
Comment
Verification Code