Explore Parsing Methods

Here in this article explore a few parsing (data conversion) methods that are very important in daily routine coding. I encountered this and as usual am sharing it with you all; how they work and the advantages.

The most frequent use of these methods is for parsing. These methods are named TryParse, ParseExact and TryParseExact.

ParseExact

Converts the specified string representation of a date and time to its DateTime equivalent using the specified format, culture-specific format information, and style. The format of the string representation must match the specified format exactly or an exception is thrown.

There are 3 overload functions for this, whilst I've used the following in my demonstration:

ParMethods1.jpg

Key Factor: When a string is expected to have a date that is always in a specified format then you should opt for ParseExact. In layman terms ParseExact implies that you want an exact parsing and there is less chance of the date being in the wrong format.

TryParseExact

It converts the specified string representation of a date and time to its DateTime equivalent using the specified format, culture-specific format information, and style. The format of the string representation must match the specified format exactly. The method returns a value that indicates whether the conversion succeeded.

ParMethods2.jpg


Key Factor: When you need DateTime.TryParseExact, you are usually dealing with invalid formats of dates, or extinct dates. If the date is in an incorrect format then DateTime.TryParseExact will return false else true.

It returns true if the string was converted successfully; otherwise, false.

The strDate parameter contains the date and time to parse and must be in a format defined by the format parameter. If you specify the wrong format (such as I gave "MM/dd/yyyy" instead of "M/dd/yyyy") then it won't parse the date and returns false and jumps into else condition as shown in the following image:

ParMethods3.jpg

TryParse

The DateTime.TryParse method converts the specified string representation to an "out" variable and returns true if it is parsed successfully, false otherwise.

ParMethods4.jpg

When strDate is a null reference, it will return 0 rather than throw an ArgumentNullException. Please have a look into the example given below:

ParMethods5.jpg

If strDate is other than a DateTime value then the "out" variable will have the default date and return false instead of throwing a formatted exception.

ParMethods6.jpg

Now it's quite easy to understand these concepts in an easier manner.

Enjoy Coding.

Up Next
    Ebook Download
    View all
    Learn
    View all