I'm kinda new to Nullable. I have a DateTime in C# that I want to be null, than assign the value in a try-catch, and after that check whether it's null or not.
Code:
DateTime? dt = null;
try
{
dt = DateTime.ParseExact(stringDate, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
}
catch(FormatException)
{
Console.WriteLine("The given string is not valid and could not be converter to a DateTime");
}
// Check if the DateTime is not null
// If it's not null, do something with the DateTime
So, my question:
Which of the two should I use, WHY should I use it, and what are the differences between the both:
if(dt != null)
{
doSomethingWithDateTime(dt);
}
Or:
if(dt.HasValue)
{
doSomethingWithDateTime(dt.Value);
}