0

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);
}
Kevin Cruijssen
  • 9,153
  • 9
  • 61
  • 135
  • 1
    How is `doSomethingWithDateTime` defined? I ask because if it is defined as taking `DateTime`, the first alternative won't even compile. Note that checking for `!= null` and `.HasValue` amounts to the same thing, the first will be autoconverted to the other. – Lasse V. Karlsen Jun 26 '14 at 07:39
  • 1
    `dt` is `DateTime?` but `dt.Value` is `DateTime`. That depends on your `doSomethingWithDateTime` implementation. Other that that, checking is `null` or not and using `.HasValue` is the same AFAIK. – Soner Gönül Jun 26 '14 at 07:40
  • @Sayse You're wrong, if it is a nullable value (like in this question), it will. – Lasse V. Karlsen Jun 26 '14 at 07:41
  • @LasseV.Karlsen - Yeah I went and double checked straight after posting that – Sayse Jun 26 '14 at 07:41
  • @LasseV.Karlsen Thanks, this is the answer to my question. If you want you can post an answer I can accept, or should I do it myself and credit you? Your call. – Kevin Cruijssen Jun 26 '14 at 07:46
  • Since it has been flagged as a duplicate, no more answers are accepted (and possibly not necessary). – Lasse V. Karlsen Jun 26 '14 at 07:46

0 Answers0