Skip to content

Instantly share code, notes, and snippets.

@jiripolasek
Last active December 9, 2024 00:07
Show Gist options
  • Save jiripolasek/b6ed6e82c6bf826318d8c0c9ef28336b to your computer and use it in GitHub Desktop.
Save jiripolasek/b6ed6e82c6bf826318d8c0c9ef28336b to your computer and use it in GitHub Desktop.
// 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.
/// </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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment