I’m designing a C#/NHibernate website that features a private messaging system. I would like admins to check if and when a message has been read by a user, and together highlight those messages that haven’t been read yet by users. To achieve both, I found two options:
Option 1
class Message
{
DateTime? Read;
}
where Read==null means not read yet
Option 2
class Message
{
DateTime Read;
}
where Read==default(DateTime) (January 1st 1 A.D., 0:00:00) means not read yet.
At university, I have been taught to use the NULL value to handle all special cases, and also using the nullable type seems a good choice since it looks easier to query for unread messages by checking whether they are NULL or not.
But, using nullable types at least involves boxing and unboxing in code, with performance decreasing. On the other hand, querying for unread messages means comparing the value (but it can be indexed)
My question is
What is your suggested approach for this? What would best practices suggest in this case?
Use
DateTime?. Its specific purpose is to avoid using reserved values (aka “magic numbers”) to represent special cases, such asnull.Also, using a nullable type introduces no boxing itself. Any values that would have been boxed still will be, but you won’t introduce any boxing simply by switching. The
Nullable<T>type is actually a struct, and the ability to compare withnull(orNothingin VB.NET) is strictly a language convention. Under the covers, it gets translated into a check on theHasValueproperty.