开发者

Is it better to use DateTime.MinValue or a nullable DateTime?

If I had a DateTime on a 开发者_JAVA百科class called "TimeLastAccessed", would it make more sense for this DateTime to be nullable:

public DateTime? TimeLastAccessed { get; set }

if (TimeLastAccessed == null) // ... handle it

to indicate it has never been accessed or check for DateTime.MinValue

public DateTime TimeLastAccessed { get; set; }

if (TimeLastAccessed == DateTime.MinValue) // ... handle it

?


It makes more sense to use Nullable. That's the idea of Nullable - to express that a value type has no valid value. To use MinValue is a patch for cases you don't have Nullable.


I agree that Nullable<DateTime> is a better choice in the absence of other considerations.

You do however need to consider other systems with which you need to interoperate.

For example:

  • if you are exposing your .NET DateTime to COM clients, you won't be able to use Nullable<DateTime>.

  • if you are storing the value in a SQL Server database, remember that SQL Server can't store DateTime.MinValue as a DateTime.

Another point to consider is that Nullable can add some complexity for callers of an API: they may need to consider how the null case should be handled. In some cases it may be simpler to use a default value for the null case. For example, consider a class that exposes a property "ExpiryDate", where a value is needed to indicate that the item never expires.

One approach is to use a Nullable<DateTime> with null representing "never expires". An alternative approach is to use a standard DateTime with DateTime.MaxValue representing "never expires".

In this example, the test for "is expired" is simpler for the standard DateTime:

if (item.ExpiryDate <= DateTime.Today) ...

than for the Nullable<DateTime>:

if (item.ExpiryDate.HasValue && item.ExpiryDate <= DateTime.Today) ...


How can something that exists never be accessed? Is your property really something list LastAccessDateByCustomerOrClient?

And in your case I think you want ...HasValue instead of == null in your test. If you're going to use the class, use the features of it to the fullest. It probably compiles to nearly the same code but ...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜