Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime.Now within a statement

Tags:

c#

.net

datetime

In the below thisIsAlwaysTrue should always be true.

DateTime d = DateTime.Now;
bool thisIsAlwaysTrue = d == d;

But does DateTime.Now work in such a way that isThisAlwaysTrue is guaranteed to be true? Or can the clock change between references to the Now property?

bool isThisAlwaysTrue = DateTime.Now == DateTime.Now;
like image 504
Jarrett Widman Avatar asked Dec 02 '22 05:12

Jarrett Widman


2 Answers

The clock can definitely change between two back-to-back calls to DateTime.Now;

like image 133
500 - Internal Server Error Avatar answered Dec 04 '22 22:12

500 - Internal Server Error


The DateTime.Now property is volatile, meaning it definitely can change between uses. But the variable you assign it to is not volatile.

So this should always set result to true:

DateTime d = DateTime.Now;
bool result = d == d;

It assigns the value returned by DateTime.Now to the d variable, not the property itself. Thus d will always equal d in that code.

But this will not always set result to true:

bool result = DateTime.Now == DateTime.Now;
like image 37
Joel Coehoorn Avatar answered Dec 04 '22 22:12

Joel Coehoorn