ValeraT1982 / ObjectsComparer

C# Framework provides mechanism to compare complex objects, allows to override comparison rules for specific properties and types.
MIT License
352 stars 86 forks source link

Problem with DateTime? Comparison #10

Closed MayurikaD closed 4 years ago

MayurikaD commented 5 years ago

I was trying to add a DynamicValueComparer to compare nullable dates, but I get an exception every time I try using this below:

var dateComparer = new DynamicValueComparer<DateTime?> ( (date1, date2, settings) => date1 != null && date2 != null && date1?.Date == date2?.Date);

Am I missing some implementation here?

ValeraT1982 commented 5 years ago

Hi @MayurikaD. What exception do you have?

I think the issue is because you use ? but not Value property for Nullable type. Try this:

DateTime? dt1 = new DateTime(2019, 1, 2);
DateTime? dt2 = new DateTime(2019, 1, 2);
var dateComparer = new DynamicValueComparer<DateTime?>
                ((date1, date2, settings) => date1 != null && date2 != null && date1.Value.Date == date2.Value.Date);

var comparer = new Comparer<DateTime?>();
comparer.AddComparerOverride<DateTime?>(dateComparer);

var result = comparer.Compare(dt1, dt2);
MayurikaD commented 5 years ago

Hi thanks for your help. So this throws a System.ArgumentException when both (or any one) values are null. image

ValeraT1982 commented 5 years ago

@MayurikaD, can you provide the callstack? In what line do you have this exception? Otherwise I'll have a look next week.

MayurikaD commented 5 years ago

@ValeraT1982 Hi here is the detail image

ValeraT1982 commented 5 years ago

@MayurikaD, try add date1.HasValue && date2.HasValue to the condition.

And condition should return true if both values are null.

If it doesn't work then I'll have a look next week.

MayurikaD commented 5 years ago

Hi, tried with the HasValue check, but it still returns the same exception.

ValeraT1982 commented 5 years ago

It looks like an issue with nulls in DynamicValueComparer. It will be fixed in the next version. As a workaround you can create class which implements AbstractValueComparer<DateTime?>and use it

ValeraT1982 commented 4 years ago

Fixed in 1.4.0