Wednesday, March 7, 2012

TryParse Methods

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.


Find how to read excel in datatable : Bulk Insertion of Data Using C# DataTable and SQL server OpenXML function

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();


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.

MSDN Referance
Char.TryParse
Guid.TryParse
DateTime.TryParseEnum.TryParse
Decimal.TryParse
Double.TryParse
IPAddress.TryParse

Note : share the information where else it is useful.

No comments:

Post a Comment