Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object.ReferenceEquals never hit

Tags:

c#

Can anyone tell me why the following condition does 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");
    }
}
like image 853
axings Avatar asked Dec 02 '22 00:12

axings


2 Answers

Because DateTime is a value type, immutable and so the references will not be equal even though the values are.

Are you meaning to do something like this? Value comparison:

if (DateTime.Compare(x, timestamps.First()) == 0)
{
    // Never hit
    Console.WriteLine("hello");
}
like image 190
Paul Sasik Avatar answered Dec 22 '22 20:12

Paul Sasik


Value types are passed and compared by value. That's why they're called "value types".

Reference types are passed and compared by reference. That's why they're called "reference types".

DateTime is a value type.

Therefore you are attempting to compare two values by reference. That's not going to work. It will always be false.

Can you explain why you'd expect something different?

like image 24
Eric Lippert Avatar answered Dec 22 '22 22:12

Eric Lippert