DateTime.Now in a statement

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 links to the Now property?

 bool isThisAlwaysTrue = DateTime.Now == DateTime.Now; 
+4
source share
4 answers

A clock can definitely switch between two callbacks on DateTime.Now;

+10
source

The DateTime.Now property is mutable, which means that it can definitely vary between uses. But the variable that you assigned is not mutable.

So, this should always lead to the fact that the result is correct:

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

It assigns the value returned by DateTime.Now to d, not the property itself. So d will always be equal to d in this code.

But this will not always result in a true result:

 bool result = DateTime.Now == DateTime.Now; 
+8
source

I would recommend you try this for yourself. This code takes part of a second in the Release assembly:

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

I hope it will play well.

+1
source

DateTime is unchanged, so it will never change after assignment. Your call to DateTime.Now does not "bind" them - it simply assigns any value to DateTime.Now when you call the variable d - it will not assign any reference.

So, if you have such a delay:

 DateTime d = DateTime.Now; // Let assume it 9:05:10 Thread.Sleep(100); Console.WriteLine(d); // will still be 9:05:10, even though it much later now 
0
source

Source: https://habr.com/ru/post/1306175/


All Articles