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();
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 ?
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.
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.
DateTime. Today is static readonly . So supposedly it should never change once (statically) instantiated.
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.
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
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.
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