tags:

views:

326

answers:

3

If I had a DateTime on a 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

?

+8  A: 

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.

Ariel
It's also too magic. What if someone wanted to express DateTime.MinValue, then it would be ignored.
Ian
A: 

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 ...

No Refunds No Returns
+1  A: 

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) ...
Joe
+1 for the Sql Server Note
The King