Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions PowerKit.Tests/Extensions/DictionaryExtensionsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,17 @@ namespace PowerKit.Tests.Extensions;

public class DictionaryExtensionsTests
{
[Fact]
public void GetValueOrNull_Test()
{
// Arrange
var source = (IDictionary<string, int>)new Dictionary<string, int> { ["one"] = 1 };

// Act & assert
source.GetValueOrNull("one").Should().Be(1);
source.GetValueOrNull("two").Should().BeNull();
}

[Fact]
public void ToDictionary_Test()
{
Expand Down
20 changes: 20 additions & 0 deletions PowerKit.Tests/Extensions/ReadOnlyDictionaryExtensionsTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using System.Collections.Generic;
using FluentAssertions;
using PowerKit.Extensions;
using Xunit;

namespace PowerKit.Tests.Extensions;

public class ReadOnlyDictionaryExtensionsTests
{
[Fact]
public void GetValueOrNull_Test()
{
// Arrange
var source = (IReadOnlyDictionary<string, int>)new Dictionary<string, int> { ["one"] = 1 };

// Act & assert
source.GetValueOrNull("one").Should().Be(1);
source.GetValueOrNull("two").Should().BeNull();
}
}
11 changes: 11 additions & 0 deletions PowerKit/Extensions/DictionaryExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,17 @@ namespace PowerKit.Extensions;
#endif
internal static class DictionaryExtensions
{
extension<TKey, TValue>(IDictionary<TKey, TValue> dictionary)
where TKey : notnull
where TValue : struct
{
/// <summary>
/// Returns the value associated with the specified key, or <see langword="null" /> if the key is not found.
/// </summary>
public TValue? GetValueOrNull(TKey key) =>
dictionary.TryGetValue(key, out var value) ? value : null;
}

extension(IDictionary dictionary)
{
/// <summary>
Expand Down
24 changes: 24 additions & 0 deletions PowerKit/Extensions/ReadOnlyDictionaryExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#nullable enable
#if NET40_OR_GREATER || NETSTANDARD || NET
Comment thread
Tyrrrz marked this conversation as resolved.
Outdated
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;

namespace PowerKit.Extensions;

#if !POWERKIT_INCLUDE_COVERAGE
[ExcludeFromCodeCoverage]
#endif
internal static class ReadOnlyDictionaryExtensions
{
extension<TKey, TValue>(IReadOnlyDictionary<TKey, TValue> dictionary)
where TKey : notnull
where TValue : struct
{
/// <summary>
/// Returns the value associated with the specified key, or <see langword="null" /> if the key is not found.
/// </summary>
public TValue? GetValueOrNull(TKey key) =>
dictionary.TryGetValue(key, out var value) ? value : null;
}
}
#endif