Tuesday, September 4, 2018

C# TryParse() Safe convertion.

TryParse() - C# best practice

TryParse() is introduce In .Net framework 2.0 for safe conversion in string to any numismatic value. and its a replacement method of Parse which exist in earlier version of .net framework.

TryParse() has many advantages ;
  • Safe to convert string to many data types (int,decimal,float,byte,Boolean,double)
  • Not throw an exception if the conversion fails.
  • Return boolean if the conversion fails.
  • Handle the null conversion. 

Why to use TryParse() instead of Parse();

Parse method will throw exception - ArgumentNullexception or FormatException or OverflowException, if the string value cannot be converted to the respective data type. so it will impact the system performance.

Explore the TryParse()
  
1:  int parsedResult;   
2:  int.TryParse("125A", out parsedResult);  
out put is

parsedResult =0


With more validation
       

string strTextData = "125A";
int parsedResult; 

if (int.TryParse(strTextData , out parsedResult))
{
   return "Valid Data";

}
else
{
 return "Invalid Data";
}