Home
Blog
Problem With DateTime.Now in C#
Updated
Dot Net Perls

Problem With DateTime.Now in C#

In C# the idea of properties is that they are externally-visible getter and setter methods that are fast to access and have no external effects. For example, the Length property on a string can be accessed, it is a simple memory load, and it won't change out from under you.

This brings us to DateTime.Now, a commonly-used property in C# on the DateTime struct. In my testing, DateTime.Now is many times slower than a memory load—this depends on the system, but it makes an OS call to get the current time. According to the rules of properties, DateTime.Now (and Today) should not even be properties.

I guess this brings us to the problem of properties in C#. Properties annoy me because:

They make no sense and are just methods in the implementation.
Even .NET breaks its own rules as the rules are difficult to follow.
Other languages like Java do not bother with properties, as they are basically not a worthwhile feature.

Another thing about properties and performance: what about a lazily-initialized field on a class? Should this be a property if it is slow to access for the first time, but fast on all following accesses? Technically, it should not be, as it is not like Length on a string. And for the same reason DateTime.Now should have been a method called DateTime.GetNow.

Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
An RSS feed is available for this blog.
Home
Changes
© 2007-2025 Sam Allen