From b95854253450ee2fe5f9a8df2c78f9e19a4732c8 Mon Sep 17 00:00:00 2001 From: Kyle Ratti Date: Tue, 19 Dec 2023 21:43:00 -0500 Subject: [PATCH] fix: rename IDictionary.TryGet to TryGetValue This resolves ambiguous invocation errors --- Base.Tests/Structures/MaybeExtensionTests.cs | 70 ++++++++++++++++++++ Base/Structures/MaybeExtensions.cs | 2 +- 2 files changed, 71 insertions(+), 1 deletion(-) diff --git a/Base.Tests/Structures/MaybeExtensionTests.cs b/Base.Tests/Structures/MaybeExtensionTests.cs index cb51573..a18f2cd 100644 --- a/Base.Tests/Structures/MaybeExtensionTests.cs +++ b/Base.Tests/Structures/MaybeExtensionTests.cs @@ -1,4 +1,6 @@ using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; using FruityFoundation.Base.Structures; using NUnit.Framework; @@ -26,4 +28,72 @@ public class MaybeExtensionTests Assert.IsNull(Maybe.Empty().ToNullable()); Assert.IsNull(Maybe.Just(0, hasValue: _ => false).ToNullable()); } + + [Test] + public void IDictionaryTests_TryGetValue_ReturnsMaybeWithValue_ForValidKey() + { + var dict = new Dictionary + { + { "one", 1 }, + { "two", 2 }, + { "three", 3 } + }; + + var result = dict.TryGetValue("one"); + + Assert.That(result, Is.InstanceOf>()); + Assert.That(result.HasValue, Is.True); + Assert.That(result.Value, Is.EqualTo(1)); + } + + [Test] + public void IDictionaryTests_TryGetValue_ReturnsEmptyMaybe_ForInvalidKey() + { + var dict = new Dictionary + { + { "one", 1 }, + { "two", 2 }, + { "three", 3 } + }; + + var result = dict.TryGetValue("eight"); + + Assert.That(result, Is.InstanceOf>()); + Assert.That(result.HasValue, Is.False); + } + + [Test] + public void IReadOnlyDictionaryTests_TryGetValue_ReturnsMaybeWithValue_ForValidKey() + { + var baseDict = new Dictionary + { + { "one", 1 }, + { "two", 2 }, + { "three", 3 } + }; + IReadOnlyDictionary dict = new ReadOnlyDictionary(baseDict); + + var result = dict.TryGet("one"); + + Assert.That(result, Is.InstanceOf>()); + Assert.That(result.HasValue, Is.True); + Assert.That(result.Value, Is.EqualTo(1)); + } + + [Test] + public void IIReadOnlyDictionaryTests_TryGetValue_ReturnsEmptyMaybe_ForInvalidKey() + { + var baseDict = new Dictionary + { + { "one", 1 }, + { "two", 2 }, + { "three", 3 } + }; + IReadOnlyDictionary dict = new ReadOnlyDictionary(baseDict); + + var result = dict.TryGet("eight"); + + Assert.That(result, Is.InstanceOf>()); + Assert.That(result.HasValue, Is.False); + } } diff --git a/Base/Structures/MaybeExtensions.cs b/Base/Structures/MaybeExtensions.cs index 200db43..d41a3e5 100644 --- a/Base/Structures/MaybeExtensions.cs +++ b/Base/Structures/MaybeExtensions.cs @@ -22,7 +22,7 @@ public static class MaybeExtensions return Maybe.Empty(); } - public static Maybe TryGet(this IDictionary dict, TKey key) => + public static Maybe TryGetValue(this IDictionary dict, TKey key) => dict.TryGetValue(key, out var value) ? Maybe.Just(value) : Maybe.Empty(); public static Maybe TryGet(this IReadOnlyDictionary dict, TKey key) =>