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)
What is your suggested approach for this? What would best practices suggest in this case?
DateTime is a Value Type like int, double etc. so there is no way to assigned a null value.
DateTime itself is a value type. It cannot be null.
Yes. If you have a nullable datetime column, then its fine.
The default and the lowest value of a DateTime object is January 1, 0001 00:00:00 (midnight). The maximum value can be December 31, 9999 11:59:59 P.M. Use different constructors of the DateTime struct to assign an initial value to a DateTime object.
Use DateTime?
. Its specific purpose is to avoid using reserved values (aka "magic numbers") to represent special cases, such as null
.
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 with null
(or Nothing
in VB.NET) is strictly a language convention. Under the covers, it gets translated into a check on the HasValue
property.
Using nullable types does not significantly "decrease performance" compared to alternative approaches. Both DateTime
and DateTime?
are structs and there is no boxing involved here. Using a nullable is the right choice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With