Skip to content

Commit

Permalink
Introduce a way to enumerate the enum values without memory allocation (
Browse files Browse the repository at this point in the history
#497)

* Add EnumerateList Method (#494)

* Revert "Add EnumerateList Method (#494)"

This reverts commit 30d46af.

* Prevent allocation when calling List

---------

Co-authored-by: Steve Smith <steve@kentsmiths.com>
  • Loading branch information
akarboush and ardalis authored Apr 28, 2024
1 parent cb3e458 commit 7396d73
Showing 1 changed file with 5 additions and 8 deletions.
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

0 comments on commit 7396d73

Please sign in to comment.