Skip to content

Commit

Permalink
Introduced new "ReadOnlySet" class and "ReadOnlySet.Empty<T>" static …
Browse files Browse the repository at this point in the history
…method

Similar to the "Enumerable.Empty<T>" and "Array.Empty" method in .NET, Skybrud.Essentials now offers a method to get an empty immutable instance of "IReadOnlySet". As the "IReadOnlySet" interface is only supported from .NET 5 and up, the new class and method is also only available for .NET 5 and up, but not .NET Framework and .NET Standard.
  • Loading branch information
abjerner committed Apr 7, 2024
1 parent 20eafee commit fc0614e
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
30 changes: 30 additions & 0 deletions src/Skybrud.Essentials/Collections/ReadOnlySet.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
#if NET5_0_OR_GREATER

using System.Collections.Generic;
using System.Collections.Immutable;

namespace Skybrud.Essentials.Collections;

/// <summary>
/// Static class for working with <see cref="IReadOnlySet{T}"/>.
/// </summary>
public static class ReadOnlySet {

/// <summary>
/// Returns an empty instance of <see cref="IReadOnlySet{T}"/>.
/// </summary>
/// <typeparam name="T">The item type of the list.</typeparam>
/// <returns>An instance of <see cref="IReadOnlySet{T}"/>.</returns>
public static IReadOnlySet<T> Empty<T>() {
return EmptyHashSet<T>.Value;
}

private static class EmptyHashSet<T> {

internal static readonly IReadOnlySet<T> Value = ImmutableHashSet.Create<T>();

}

}

#endif
20 changes: 20 additions & 0 deletions src/TestProject1/Collections/ReadOnlySetTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using Skybrud.Essentials.Collections;

namespace TestProject1.Collections;

[TestClass]
public class ReadOnlySetTests {

[TestMethod]
public void Empty() {

var a = ReadOnlySet.Empty<string>();
var b = ReadOnlySet.Empty<string>();

Assert.AreEqual(a, b);

Assert.AreEqual(a.GetHashCode(), b.GetHashCode());

}

}

0 comments on commit fc0614e

Please sign in to comment.