Skip to content

Commit

Permalink
Add EnumerateList Method (ardalis#494)
Browse files Browse the repository at this point in the history
  • Loading branch information
akarboush authored Feb 21, 2024
1 parent b58aa46 commit 30d46af
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
14 changes: 10 additions & 4 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 @@ -93,6 +93,12 @@ private static IEqualityComparer<TValue> GetValueComparer()
.ToList()
.AsReadOnly();

/// <summary>
/// Enumerates through all the instances of <see cref="SmartEnum{TEnum, TValue}"/>.
/// </summary>
/// <returns>An <see cref="IEnumerable{TEnum}"/> containing all the instances of <see cref="SmartEnum{TEnum, TValue}"/>.</returns>
public static IEnumerable<TEnum> EnumerateList() => _fromName.Value.Values;

private readonly string _name;
private readonly TValue _value;

Expand Down Expand Up @@ -433,7 +439,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
24 changes: 24 additions & 0 deletions test/SmartEnum.UnitTests/SmartEnumEnumerateList.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
namespace Ardalis.SmartEnum.UnitTests
{
using FluentAssertions;
using Xunit;

public class SmartEnumEnumerateList
{
[Fact]
public void ReturnsSameValuesAsListForAllDefinedSmartEnums()
{
var result = TestEnum.EnumerateList();

result.Should().BeEquivalentTo(TestEnum.List);
}

[Fact]
public void ReturnsSameValuesAsListForAllBaseAndDerivedSmartEnums()
{
var result = TestBaseEnumWithDerivedValues.EnumerateList();

result.Should().BeEquivalentTo(TestBaseEnumWithDerivedValues.List);
}
}
}

0 comments on commit 30d46af

Please sign in to comment.