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");
}