From 30d46af71580c7f816fea52e563a0d561d4b8a23 Mon Sep 17 00:00:00 2001 From: "A. Karboush" <40485241+akarboush@users.noreply.github.com> Date: Wed, 21 Feb 2024 08:06:56 +0100 Subject: [PATCH] Add EnumerateList Method (#494) --- src/SmartEnum/SmartEnum.cs | 14 +++++++---- .../SmartEnumEnumerateList.cs | 24 +++++++++++++++++++ 2 files changed, 34 insertions(+), 4 deletions(-) create mode 100644 test/SmartEnum.UnitTests/SmartEnumEnumerateList.cs diff --git a/src/SmartEnum/SmartEnum.cs b/src/SmartEnum/SmartEnum.cs index f1a5f012..067fb699 100644 --- a/src/SmartEnum/SmartEnum.cs +++ b/src/SmartEnum/SmartEnum.cs @@ -38,15 +38,15 @@ protected SmartEnum(string name, int value) : /// The type of the inner value. /// public abstract class SmartEnum : - ISmartEnum, + ISmartEnum, IEquatable>, IComparable> where TEnum : SmartEnum where TValue : IEquatable, IComparable { - static readonly Lazy _enumOptions = + static readonly Lazy _enumOptions = new Lazy(GetAllOptions, LazyThreadSafetyMode.ExecutionAndPublication); - + static readonly Lazy> _fromName = new Lazy>(() => _enumOptions.Value.ToDictionary(item => item.Name)); @@ -93,6 +93,12 @@ private static IEqualityComparer GetValueComparer() .ToList() .AsReadOnly(); + /// + /// Enumerates through all the instances of . + /// + /// An containing all the instances of . + public static IEnumerable EnumerateList() => _fromName.Value.Values; + private readonly string _name; private readonly TValue _value; @@ -433,7 +439,7 @@ public virtual int CompareTo(SmartEnum other) => [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator TValue(SmartEnum smartEnum) => smartEnum is not null - ? smartEnum._value + ? smartEnum._value : default; /// diff --git a/test/SmartEnum.UnitTests/SmartEnumEnumerateList.cs b/test/SmartEnum.UnitTests/SmartEnumEnumerateList.cs new file mode 100644 index 00000000..c47a0b47 --- /dev/null +++ b/test/SmartEnum.UnitTests/SmartEnumEnumerateList.cs @@ -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); + } + } +}