1

I would like to initialize a DateTime value object with a value that does not represent a valid date because I need to distinguish an invalid or unset date from any valid value. For floating point numbers I would use not-a-number values like in this example:

Double value = Double.NaN;

Is there a similar value for DateTime objects in c#? For example something like that:

DateTime datval = DateTime.Invalid;
Georg W.
  • 1,292
  • 10
  • 27
  • 4
    Why not `DateTime?` or `MinDate` ? – TheGeneral Sep 24 '19 at 07:15
  • 6
    use nullable: `DateTime?` Then you can use `datval.HasValue` – phuzi Sep 24 '19 at 07:15
  • "invalid" is a *vouge* word for `DateTime` instance since it always represents a point with date and time parts. Under the hood, it based on `Ticks` which is a long number and "invalid" term doesn't much meaning for it. You have a few options in my opinion; - You can use nullable DateTime as `DateTime?` and then in can be *assignable* to `null`. - Or you can use `DateTime.MinValue` (but of course, this can be change which depends on what you mean by "invalid") – Soner Gönül Sep 24 '19 at 07:19
  • Thank you for the duplicate marking. I could not find the other answer because I was searching for "invalid value" but not for "null value". – Georg W. Sep 24 '19 at 07:25

1 Answers1

2

The easiest way is to use a nullable data type - DateTime?. The same approach works with double? and is generally a better idea than using NaN, if you can.

If you can't use DateTime? for some reason, DateTime.MinValue is often used to mean invalid date. However, it still needs special handling in your code, just like double.NaN. Both allow valid arithmetic on the value, and may lead to unexpected overflows or other exceptions.

Finally, you can always make your own helper class. Something like

public class PossiblyEmpty<T> where T : struct
{
  private readonly bool hasValue;
  private readonly T value;

  public PossiblyEmpty(T value)
  {
    this.value = value;
    this.hasValue = true;
  }

  public PossiblyEmpty() { }

  public bool HasValue => hasValue;
  public T Value => hasValue ? value : throw new InvalidOperationException("No value");
}
Luaan
  • 62,244
  • 7
  • 97
  • 116
  • Great hint! (off topic: For doubles I still prefer NaN because they can be used in calculations and produce an expectable result.) – Georg W. Sep 24 '19 at 07:18
  • @GeorgW. Yeah, that's exactly why I prefer *not* to use NaN :D If there's some unexpected input, and it's not explicitly expected and dealt with accordingly, I prefer to fail early. But each approach has their benefits and drawbacks, of course. – Luaan Sep 24 '19 at 07:22