tags:

views:

107

answers:

4

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;
+11  A: 

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

500 - Internal Server Error
+6  A: 

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;
Joel Coehoorn
A: 

DateTime is immutable, so it will never ever change once assigned. Your call to DateTime.Now doesn't "link" them - it just assigns whatever value DateTime.Now is at the time of calling to the variable d - it will not assign some sort of reference.

So if you have a delay like this:

DateTime d = DateTime.Now; // Let's assume it's 9:05:10
Thread.Sleep(100);
Console.WriteLine(d); // will still be 9:05:10, even though it's much later now
Michael Stum
+1  A: 

I would have to recommend you try this for yourself. This code takes a fraction of second in the Release build:

using System;

class Program {
  static void Main(string[] args) {
    while (DateTime.UtcNow == DateTime.UtcNow) ;
    Console.WriteLine("oops");
    Console.ReadLine();
  }
}

I trust it will repro well.

Hans Passant