How to manage parsing an null object for DateTime to be used with ADO.NET as DBNULL

GivenPie picture GivenPie · Nov 25, 2012 · Viewed 35.3k times · Source

I have two DateTime objects, BirthDate and HireDate. They are correctly formatted as a string and when I pass them through to my data access layer, they need to be parsed into a DateTime object.

DateTime hD = DateTime.Parse(hire);            
DateTime bD = DateTime.Parse(birth);

//incase of a datestring being passed through
dateStringPassed = "7/2/1969";

But sometimes, the strings hire and birth are null or empty "", if the code is run like this, I get a FormatException error from Parsing a empty string. How can I manage empty parses and allow the DateTime, if empty or null, be accepted as DBNull.Value?

I still cannot manage incase the user does not pass through a DateTime string, then the parse crashes my code.

My parameter for birth date is as follows and checks the variable if null, then use DBNull.Value.

Answer

Honza Brestan picture Honza Brestan · Nov 25, 2012

The Parse method can't handle empty strings, but you can use nullable DateTime and do something like this:

DateTime? hD = String.IsNullOrEmpty(hire) ? (DateTime?)null : DateTime.Parse(hire)

But even safer would be using TryParse instead:

DateTime? hD = null;
DateTime.TryParse(hire, out hD);

Then for storing this value, you can test hD.HasValue:

if(hD.HasValue) { /* use hD */ }
else { /* else use DBNull.Value */ }

Since C# 7, you can use shorter syntax for inline out parameters and you can avoid nullable type altogether:

if (DateTime.TryParse(hire, out var hD)) { /* use hD */ }
else { /* use DBNull.Value */ }