Skip to content

Instantly share code, notes, and snippets.

@jiripolasek
Last active December 9, 2024 00:07

Revisions

  1. jiripolasek revised this gist Dec 9, 2024. 1 changed file with 14 additions and 0 deletions.
    14 changes: 14 additions & 0 deletions Freezer.cs
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,17 @@
    // HashSet supports collection initializer syntax
    private static readonly HashSet<string> abcCollection1 = ["a", "b", "c"];
    private static readonly FrozenSet<string> abcCollection2 = ["a", "b", "c"]; // doesn't work, yet...

    // example with freezer:
    private static readonly FrozenSet<FileAttributes> allowedAttributes = Freeze(FileAttributes.Archive, FileAttributes.Device, FileAttributes.Hidden);
    private static readonly FrozenSet<string> allowedKeywords = Freeze(StringComparer.OrdinalIgnoreCase, "squirrel", "cat", "dog");

    // example without:
    private static readonly FrozenSet<FileAttributes> allowedAttributesUgly = new HashSet<FileAttributes>([FileAttributes.Archive, FileAttributes.Device, FileAttributes.Hidden]).ToFrozenSet();
    private static readonly FrozenSet<string> allowedKeywordsUgly = new HashSet<string>(["squirrel", "cat", "dog"]).ToFrozenSet(StringComparer.OrdinalIgnoreCase);



    #if NET8_0_OR_GREATER
    /// <summary>
    /// Provides a set of static methods for creating frozen sets with a readable syntax in field / property initialization.
  2. jiripolasek created this gist Dec 8, 2024.
    26 changes: 26 additions & 0 deletions Freezer.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,26 @@
    #if NET8_0_OR_GREATER
    /// <summary>
    /// Provides a set of static methods for creating frozen sets with a readable syntax in field / property initialization.
    /// </summary>
    internal static class Freezer
    {
    /// <summary>
    /// Creates a new <see cref="FrozenSet{T}"/> from the specified elements.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="enumerable"></param>
    /// <returns></returns>
    public static FrozenSet<T> From<T>(params IEnumerable<T> enumerable)
    {
    return enumerable.ToFrozenSet();
    }

    /// <summary>
    /// Creates a new <see cref="FrozenSet{T}"/> from the specified elements.
    /// </summary>
    public static FrozenSet<T> From<T>(IEqualityComparer<T> comparer, params IEnumerable<T> enumerable)
    {
    return enumerable.ToFrozenSet(comparer);
    }
    }
    #endif