Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce a way to enumerate the enum values without memory allocation #497

Merged
merged 4 commits into from
Apr 28, 2024
Merged
Changes from all 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
13 changes: 5 additions & 8 deletions src/SmartEnum/SmartEnum.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,15 +38,15 @@ protected SmartEnum(string name, int value) :
/// <typeparam name="TValue">The type of the inner value.</typeparam>
/// <remarks></remarks>
public abstract class SmartEnum<TEnum, TValue> :
ISmartEnum,
ISmartEnum,
IEquatable<SmartEnum<TEnum, TValue>>,
IComparable<SmartEnum<TEnum, TValue>>
where TEnum : SmartEnum<TEnum, TValue>
where TValue : IEquatable<TValue>, IComparable<TValue>
{
static readonly Lazy<TEnum[]> _enumOptions =
static readonly Lazy<TEnum[]> _enumOptions =
new Lazy<TEnum[]>(GetAllOptions, LazyThreadSafetyMode.ExecutionAndPublication);

static readonly Lazy<Dictionary<string, TEnum>> _fromName =
new Lazy<Dictionary<string, TEnum>>(() => _enumOptions.Value.ToDictionary(item => item.Name));

Expand Down Expand Up @@ -88,10 +88,7 @@ private static IEqualityComparer<TValue> GetValueComparer()
/// </summary>
/// <value>A <see cref="IReadOnlyCollection{TEnum}"/> containing all the instances of <see cref="SmartEnum{TEnum, TValue}"/>.</value>
/// <remarks>Retrieves all the instances of <see cref="SmartEnum{TEnum, TValue}"/> referenced by public static read-only fields in the current class or its bases.</remarks>
public static IReadOnlyCollection<TEnum> List =>
_fromName.Value.Values
.ToList()
.AsReadOnly();
public static IReadOnlyCollection<TEnum> List => _enumOptions.Value;

private readonly string _name;
private readonly TValue _value;
Expand Down Expand Up @@ -433,7 +430,7 @@ public virtual int CompareTo(SmartEnum<TEnum, TValue> other) =>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static implicit operator TValue(SmartEnum<TEnum, TValue> smartEnum) =>
smartEnum is not null
? smartEnum._value
? smartEnum._value
: default;

/// <summary>
Expand Down
Loading