Difference between Parse/TryParse/ParseExact/TryParseExact

Parse
=====

//int.Parse("12.44");

//Exception : Above code will generate the exception "Input string was not in a correct format", just because you are trying to cast float/real value in int[Integer].
//Only it is parsing if your parameter value must match the desire type in which you are trying to parse.


TryParse
========
//case #1

int.TryParse("14.55",out a);

//case #2
int.TryParse("14", out a);


//Above code(case 1) will return 'false', just because parsing operation gets failed and value for variable 'a' would be 'zero'
//here consider 'a' is output type of parameter like we have in oracle/sql server(not exactly same but behavior is same).
//if parsing get succeeded than it will return true and target variable (i.e. 'a') will have the parsed value, like in case #2 'a' will return 14
// Difference between out and ref type
//ref: parameter variable need to be assigned before passing to called function otherwise u will get the compile time error/there is no compulsion for called function to assign value in ref type parameter variable
//out: parameter variable need not to be assigned before passing in the called function but here we have compulsion for called method to assign a value in out type parameter variable before control leaves the current method as compile time error comes.


ParseExact
==========
Here I am taking a datetime example because I think it is easy for me to clear the behavior of this method.

Lets consider two case here...

Case 1: You have a date in some peculiar format like

string dateString = "Mon 16 Jun 8:30 AM 2008"; /// i am sure this is not normal format or u have date in some other format
Now ur objective is to parse it in some other format
Normally what we do is

System.DateTime dt = DateTime.Parse(dateString).ToString("dd-MMM-yyyy") /// here dd-MMM-yyyy is my desired format

DateTime.Parse // MSDN: Because the Parse(String) method tries to parse the string representation of a date and time using the formatting rules of the current culture, trying to parse a particular string across different cultures can either fail or return different results If a specific date and time format will be parsed across different locales, use the DateTime.Parse(String, IFormatProvider) method or one of the overloads of the ParseExact method and provide a format specifier.

But when u try to run this code it will give you an exception "String was not recognized as a valid DateTime"

Case 2:
string dateString = "Mon 16 Jun 8:30 AM 2008"; // Any Custom formatted date
string dateformat = "ddd dd MMM h:mm tt yyyy"; // Here your format must match the date that you have mentioned above

Response.Write(DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture).ToString("dd-MMM-yyyy")); /// Now..Here you go

CultureInfo.InvariantCulture /// Culture Independent


TryParseExact
=============

Case #1: You have a date in this format
string dateString = "Mon 16 Jun 8:30 AM 2008"; /// i am sure this is not a normal format or u consider a date in someother format
string dateformat = "ddd dd MMM h:mm tt yyyy"; // Here your format must match the date that you have mentioned above

DateTime dt;

if (DateTime.TryParseExact(dateString, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
Response.Write("After Parsed : " + dt.ToString("dd-MMM-yyyy"));
else
Response.Write("Parsing Failed:" + dt.ToString("dd-MMM-yyyy"));

Here the output would be "After Parsed : " + , because your target date is exactly matched the format that you mentioned.

Case #2:
Consider the first case and just change the format

so, now my date format is
string dateformat = "dd ddd MMM h:mm tt yyyy";


if (DateTime.TryParseExact(dateString, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
Response.Write("After Parsed : " + dt.ToString("dd-MMM-yyyy"));
else
Response.Write("Parsing Failed:" + dt.ToString("dd-MMM-yyyy"));

Here the output would be "Parsing Failed : 01-Jan-0001", because your target date is not exactly matched as the format that you mentioned.





Here I tried to clear myself with simplest example of this subtle difference. I know there is lots of scope to enhance this post but my objective was to take the difference part only.
Please post your feedback …

Comments

Post a Comment

Popular posts from this blog

Benefits of Test Driven Development (TDD)

Version history of C#