Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is DateTime.Now a property and not a method?

Tags:

c#

.net

datetime

After reading this blog entry : http://wekeroad.com/post/4069048840/when-should-a-method-be-a-property,

I'm wondering why Microsoft choose in C# :

DateTime aDt = DateTime.Now; 

instead of

DateTime aDt = DateTime.Now(); 
  • Best practices say : Use a method when calling the member twice in succession produces different results
  • And DateTime.Now is perfect example of non-determistic method/property.

Do you know if there any reason for that design ?
Or if it's just a small mistake ?

like image 452
Jonas at Software Journey Avatar asked Mar 25 '11 20:03

Jonas at Software Journey


People also ask

Should I use DateTime now?

You should always try to work with DateTime objects that have Kind=Utc , except during i/o (displaying and parsing). This means you should almost always be using DateTime. UtcNow , except for the cases where you're creating the object just to display it, and discard it right away.

Why DateTime is a structure?

The actual data in a DateTime is a single long integer. If it were a class, every time you created a new object, 8 bytes would be allocated on the heap and another 8 bytes would be allocated on the stack for the pointer. So by making a DateTime a struct, it effectively cuts the memory requirements in half.

Is DateTime now static?

DateTime. Today is static readonly . So supposedly it should never change once (statically) instantiated.

What is the use of date/time properties?

DateTime Properties It contains properties like Day, Month, Year, Hour, Minute, Second, DayOfWeek and others in a DateTime object. It specifies day of the week like Sunday, Monday etc. It is an enum which starts from Sunday to Saturday.


2 Answers

I believe in CLR via C#, Jeffrey Richter mentions that DateTime.Now is a mistake.

The System.DateTime class has a readonly Now property that returns the current date and time. Each time you query this property, it will return a different value. This is a mistake, and Microsoft wishes that they could fix the class by making Now a method instead of a property.

CLR via C# 3rd Edition - Page 243

like image 148
devdigital Avatar answered Sep 21 '22 08:09

devdigital


It actually is deterministic; it's output is not random, but is based on something quite predictable.

The 'current time' changes all the time; so to be relatively "the same" with each call, that value must change so that every time it's called, it's returning the current time.

EDIT:

This just occurred to me: Of course, two subsequent calls to a property getter can return different results, if something changed the property value in the interim. Properties are not supposed to be Constants.

So, that's what happening (conceptually) with DateTime.Now; its value is being changed between subsequent calls to it.

like image 23
Andrew Barber Avatar answered Sep 23 '22 08:09

Andrew Barber