Frustrations with System.DateTime - Part 1
System.DateTime
is a frustrating object for a number of reasons, many of
which I hope to elaborate in future posts.
Imagine you have a class, that for correctness, requires a DateTime
parameter
to be in UTC. How can you communicate and enforce this fact to users of your
class?
Unfortunately, there is nothing like a UtcDateTime
class in the .NET BCL. You’re basically
stuck with the following:
public class Dater
{
public Dater(DateTime createdDateUtc)
{
if (createdDateUtc.Kind != DateTimeKind.Utc)
throw new ArgumentException("createdDateUtc must be a UTC time");
// ...
}
}
There are only two signals to future programmers:
- the “Utc” suffix on your parameter name
- the
ArgumentException
You have absolutely no way to enforce at compile time that someone actually passed you the UTC time you need. Relying on exceptions and parameter names is confusing and error prone.