From 98dc557a017c00fb66c4cfb19a5aee6c3b8abc03 Mon Sep 17 00:00:00 2001 From: Vladimir Date: Tue, 3 Nov 2020 16:04:04 -0500 Subject: [PATCH] #237 ValueObject : IComparable is Potentially Breaking due to Type Ambiguity --- .../ValueObjectTests/IComparableTests.cs | 9 +++------ CSharpFunctionalExtensions/ValueObject/ValueObject.cs | 9 +++------ version.txt | 2 +- 3 files changed, 7 insertions(+), 13 deletions(-) diff --git a/CSharpFunctionalExtensions.Tests/ValueObjectTests/IComparableTests.cs b/CSharpFunctionalExtensions.Tests/ValueObjectTests/IComparableTests.cs index f2d4ab12..6d366f5e 100644 --- a/CSharpFunctionalExtensions.Tests/ValueObjectTests/IComparableTests.cs +++ b/CSharpFunctionalExtensions.Tests/ValueObjectTests/IComparableTests.cs @@ -68,17 +68,14 @@ public void Can_sort_value_objects_containing_nulls() } [Fact] - public void Sorting_value_objects_returns_same_collection_if_one_of_properties_doesnt_implement_IComparable() + public void Two_value_objects_are_not_equal_if_they_contain_non_comparable_components_of_different_values() { var vo1 = new VOWithObjectProperty(new object()); var vo2 = new VOWithObjectProperty(new object()); - VOWithObjectProperty[] array = new[] { vo1, vo2 } - .OrderBy(x => x) - .ToArray(); + int result = vo1.CompareTo(vo2); - array[0].Should().Be(vo1); - array[1].Should().Be(vo2); + result.Should().NotBe(0); } private class VOWithObjectProperty : ValueObject diff --git a/CSharpFunctionalExtensions/ValueObject/ValueObject.cs b/CSharpFunctionalExtensions/ValueObject/ValueObject.cs index e47e335c..e87686a1 100644 --- a/CSharpFunctionalExtensions/ValueObject/ValueObject.cs +++ b/CSharpFunctionalExtensions/ValueObject/ValueObject.cs @@ -129,13 +129,10 @@ private int CompareComponents(object object1, object object2) if (object2 is null) return 1; - var component1 = object1 as IComparable; - var component2 = object2 as IComparable; + if (object1 is IComparable comparable1 && object2 is IComparable comparable2) + return comparable1.CompareTo(comparable2); - if (component1 == null || component2 == null) - return 0; - - return component1.CompareTo(component2); + return object1.Equals(object2) ? 0 : -1; } public int CompareTo(ValueObject other) diff --git a/version.txt b/version.txt index 250c60bb..b288a186 100644 --- a/version.txt +++ b/version.txt @@ -1,4 +1,4 @@ -2.12.1 +2.12.2 New features: * None