Object.ReferenceEquals never hit

Can someone tell me why the following condition did not hit?

List<DateTime> timestamps = new List<DateTime>(); timestamps.Add(DateTime.Parse("8/5/2011 4:34:43 AM")); timestamps.Add(DateTime.Parse("8/5/2011 4:35:43 AM")); foreach(DateTime x in timestamps) { if (Object.ReferenceEquals(x, timestamps.First())) { // Never hit Console.WriteLine("hello"); } } 
+4
source share
5 answers

Since DateTime is a value type, immutable, and therefore the links will not be equal even if there are values.

Do you want to do something like this? Comparison of values:

 if (DateTime.Compare(x, timestamps.First()) == 0) { // Never hit Console.WriteLine("hello"); } 
+7
source

Value types are transmitted and compared by value. That is why they are called "value types".

Link types are passed and compared by reference. That is why they are called "reference types."

DateTime is the type of value.

Therefore, you are trying to compare two values ​​by reference. This will not work. It will always be false.

Can you explain why you expect something else?

+6
source

I think a number of other answers missed something.

In the case of object.ReferenceEquals(object,object) any types of values ​​are "placed" in objects, and these (new) objects are passed. Consider the following:

 DateTime d1 = DateTime.MinValue; DateTime d2 = d1; object ob1 = (object)d1; // boxed! object ob2 = ob1; // false - the values in d1 and d2 are BOXED to (new) different objects object.ReferenceEquals(d1, d2); // false - same as above, although I am not sure sure if a // VM implementation could re-use a BOXED object object.ReferenceEquals(d1, d1); // true - naturally - BOXED only once at "boxed!" (same object!) object.ReferenceEquals(ob1, ob2); 

Happy coding.


Related: Marc responds to a Vs Reference Type - Object Class C # Value Type , where it talks about box conversion .

+3
source

They have the same meaning, but they are not the same reference.

Take a look at the MSDN entry for Object.ReferenceEquals

In addition, even if you were comparing the same object, you still would not hit it by comparing references, because DateTime structure, that is, a value type. Value Types , by definition, copy the contained value, not a reference to an object (for example, Reference Types do).

+1
source

Objects are first copied inside ReferenceEquals because they are of type value, so references are never equal.

0
source

All Articles