From 27e11150b78f0b62071de74f48bf3248d167e120 Mon Sep 17 00:00:00 2001 From: Steven Kirk Date: Thu, 30 Jan 2020 11:52:13 +0100 Subject: [PATCH] Make comparing IndexPath with null do something useful. --- src/Avalonia.Controls/IndexPath.cs | 7 +++++++ .../Avalonia.Controls.UnitTests/IndexPathTests.cs | 14 ++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/src/Avalonia.Controls/IndexPath.cs b/src/Avalonia.Controls/IndexPath.cs index 32d8c2b051..6c5aaf7ad1 100644 --- a/src/Avalonia.Controls/IndexPath.cs +++ b/src/Avalonia.Controls/IndexPath.cs @@ -58,6 +58,11 @@ namespace Avalonia.Controls public int GetAt(int index) { + if (index >= GetSize()) + { + throw new IndexOutOfRangeException(); + } + return _path?[index] ?? (_index - 1); } @@ -169,5 +174,7 @@ namespace Avalonia.Controls public static bool operator >=(IndexPath x, IndexPath y) { return x.CompareTo(y) >= 0; } public static bool operator ==(IndexPath x, IndexPath y) { return x.CompareTo(y) == 0; } public static bool operator !=(IndexPath x, IndexPath y) { return x.CompareTo(y) != 0; } + public static bool operator ==(IndexPath? x, IndexPath? y) { return (x ?? default).CompareTo(y ?? default) == 0; } + public static bool operator !=(IndexPath? x, IndexPath? y) { return (x ?? default).CompareTo(y ?? default) != 0; } } } diff --git a/tests/Avalonia.Controls.UnitTests/IndexPathTests.cs b/tests/Avalonia.Controls.UnitTests/IndexPathTests.cs index 190e92ed5e..1e4aa0a2b8 100644 --- a/tests/Avalonia.Controls.UnitTests/IndexPathTests.cs +++ b/tests/Avalonia.Controls.UnitTests/IndexPathTests.cs @@ -77,5 +77,19 @@ namespace Avalonia.Controls.UnitTests Assert.Equal(0, a.CompareTo(b)); Assert.Equal(a.GetHashCode(), b.GetHashCode()); } + + [Fact] + public void Null_Equality() + { + var a = new IndexPath(null); + var b = new IndexPath(1); + + // Implementing operator == on a struct automatically implements an operator which + // accepts null, so make sure this does something useful. + Assert.True(a == null); + Assert.False(a != null); + Assert.False(b == null); + Assert.True(b != null); + } } }