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");
}
}
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");
}
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With