├── test ├── EnumUtilitiesGenerator.Tests │ ├── EnumUtilitiesGeneratorTest.cs │ └── EnumUtilitiesGenerator.Tests.csproj ├── ConsoleApp │ ├── Program.cs │ ├── PaymentMethodIgnore.cs │ ├── PaymentMethodThrow.cs │ ├── PaymentMethodUseItself.cs │ └── ConsoleApp.csproj └── Benchmark │ ├── Program.cs │ ├── FewMembersEnum.cs │ ├── Benchmark.csproj │ ├── EnumUtils.cs │ ├── Benchmarker.cs │ └── ManyMembersEnum.cs ├── src └── EnumUtilitiesGenerator │ ├── StringExtensions.cs │ ├── ServicesReceiver.cs │ ├── EnumUtilitiesGenerator.csproj │ ├── Constants.cs │ ├── SwitchesBuilder.cs │ └── EnumHelperGenerator.cs ├── .gitattributes ├── EnumUtilitiesGenerator.sln ├── README.md └── .gitignore /test/EnumUtilitiesGenerator.Tests/EnumUtilitiesGeneratorTest.cs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leoformaggi/enum-utilities-generator/HEAD/test/EnumUtilitiesGenerator.Tests/EnumUtilitiesGeneratorTest.cs -------------------------------------------------------------------------------- /test/ConsoleApp/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace ConsoleApp 4 | { 5 | class Program 6 | { 7 | static void Main(string[] args) 8 | { 9 | Console.WriteLine("Hello World!"); 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /test/Benchmark/Program.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Running; 2 | 3 | namespace Benchmark 4 | { 5 | class Program 6 | { 7 | static void Main(string[] args) 8 | { 9 | BenchmarkRunner.Run(); 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/EnumUtilitiesGenerator/StringExtensions.cs: -------------------------------------------------------------------------------- 1 | namespace EnumUtilitiesGenerator 2 | { 3 | internal static class StringExtensions 4 | { 5 | public static string Quote(this string s) 6 | { 7 | return $"\"{s}\""; 8 | } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /test/ConsoleApp/PaymentMethodIgnore.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | 3 | namespace SourceGeneratorTest.Console 4 | { 5 | [GenerateHelper(GenerateHelperOption.IgnoreEnumWithoutDescription)] 6 | public enum PaymentMethodIgnore 7 | { 8 | [Description("Credit card")] 9 | Credit, 10 | 11 | [Description("Debit card")] 12 | Debit, 13 | 14 | Cash 15 | } 16 | } -------------------------------------------------------------------------------- /test/ConsoleApp/PaymentMethodThrow.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | 3 | namespace SourceGeneratorTest.Console 4 | { 5 | [GenerateHelper(GenerateHelperOption.ThrowForEnumWithoutDescription)] 6 | public enum PaymentMethodThrow 7 | { 8 | [Description("Credit card")] 9 | Credit, 10 | 11 | [Description("Debit card")] 12 | Debit, 13 | 14 | Cash 15 | } 16 | } -------------------------------------------------------------------------------- /test/ConsoleApp/PaymentMethodUseItself.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | 3 | namespace SourceGeneratorTest.Console 4 | { 5 | [GenerateHelper(GenerateHelperOption.UseItselfWhenNoDescription)] 6 | public enum PaymentMethodUseItself 7 | { 8 | [Description("Credit card")] 9 | Credit, 10 | 11 | [Description("Debit card")] 12 | Debit, 13 | 14 | Cash 15 | } 16 | } -------------------------------------------------------------------------------- /test/ConsoleApp/ConsoleApp.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net5.0 6 | 7 | 8 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /test/Benchmark/FewMembersEnum.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | 3 | namespace Benchmark 4 | { 5 | [GenerateHelper(GenerateHelperOption.UseItselfWhenNoDescription)] 6 | public enum FewMembersEnum 7 | { 8 | [Description("Test00")] Test00, 9 | [Description("Test01")] Test01, 10 | [Description("Test02")] Test02, 11 | [Description("Test03")] Test03, 12 | [Description("Test04")] Test04, 13 | [Description("Test05")] Test05 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /test/Benchmark/Benchmark.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net5.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /src/EnumUtilitiesGenerator/ServicesReceiver.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.CodeAnalysis; 2 | using Microsoft.CodeAnalysis.CSharp.Syntax; 3 | using System.Collections.Generic; 4 | 5 | namespace EnumUtilitiesGenerator 6 | { 7 | internal class ServicesReceiver : ISyntaxReceiver 8 | { 9 | public List EnumsToGenerate { get; } = new(); 10 | 11 | public void OnVisitSyntaxNode(SyntaxNode syntaxNode) 12 | { 13 | if (syntaxNode is EnumDeclarationSyntax eds) 14 | EnumsToGenerate.Add(eds); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /test/EnumUtilitiesGenerator.Tests/EnumUtilitiesGenerator.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net5.0 5 | 6 | false 7 | 8 | 9 | 10 | Library 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | runtime; build; native; contentfiles; analyzers; buildtransitive 21 | all 22 | 23 | 24 | runtime; build; native; contentfiles; analyzers; buildtransitive 25 | all 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /src/EnumUtilitiesGenerator/EnumUtilitiesGenerator.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | latest 6 | enable 7 | true 8 | Leonardo Formaggi 9 | 10 | true 11 | 12 | EnumUtilitiesGenerator is a small source generator lib that generates a helper class for each enum with a specific attribute in the consuming project. The helper class provide a compile-time map between enum members and their DescriptionAttribute value. 13 | MIT 14 | https://github.com/leoformaggi/enum-utilities-generator 15 | https://github.com/leoformaggi/enum-utilities-generator.git 16 | git 17 | source generator 18 | 0.1.6 19 | true 20 | true 21 | 22 | 23 | 24 | 25 | 26 | 27 | all 28 | runtime; build; native; contentfiles; analyzers; buildtransitive 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /test/Benchmark/EnumUtils.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel; 4 | using System.Reflection; 5 | 6 | namespace Benchmark 7 | { 8 | public static class EnumUtils 9 | { 10 | public static string GetDescriptionFromEnum(this Enum value) 11 | { 12 | DescriptionAttribute[] array = (DescriptionAttribute[])value.GetType().GetField(value.ToString())!.GetCustomAttributes(typeof(DescriptionAttribute), inherit: false); 13 | if (array != null && array.Length != 0) 14 | { 15 | return array[0].Description; 16 | } 17 | 18 | return string.Empty; 19 | } 20 | 21 | public static T GetEnumFromDescription(string description) 22 | { 23 | return GetEnumFromDescription(description, notFoundReturnDefault: true); 24 | } 25 | 26 | public static T GetEnumFromDescription(string description, bool notFoundReturnDefault) 27 | { 28 | Type typeFromHandle = typeof(T); 29 | if (!typeFromHandle.IsEnum) 30 | { 31 | throw new ArgumentException("T must be an enumerated type."); 32 | } 33 | 34 | FieldInfo[] fields = typeFromHandle.GetFields(); 35 | foreach (FieldInfo fieldInfo in fields) 36 | { 37 | DescriptionAttribute descriptionAttribute = Attribute.GetCustomAttribute(fieldInfo, typeof(DescriptionAttribute)) as DescriptionAttribute; 38 | if (descriptionAttribute != null && descriptionAttribute.Description == description) 39 | { 40 | return (T)fieldInfo.GetValue(null); 41 | } 42 | } 43 | 44 | if (notFoundReturnDefault) 45 | { 46 | return default(T); 47 | } 48 | 49 | throw new KeyNotFoundException(description + " not found in " + typeof(T).Name); 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/EnumUtilitiesGenerator/Constants.cs: -------------------------------------------------------------------------------- 1 | namespace EnumUtilitiesGenerator 2 | { 3 | internal class Constants 4 | { 5 | public const string GENERATEHELPER_FULL_NAME = "GenerateHelperAttribute"; 6 | public const string GENERATEHELPER_NAME = "GenerateHelper"; 7 | 8 | public const string GENERATEHELPER_ATTRIBUTE = @"// 9 | using System; 10 | 11 | [AttributeUsage(AttributeTargets.Enum, AllowMultiple = false, Inherited = false)] 12 | public sealed class GenerateHelperAttribute : Attribute 13 | { 14 | public GenerateHelperAttribute(GenerateHelperOption generationOption) 15 | { 16 | GenerationOption = generationOption; 17 | } 18 | 19 | public GenerateHelperOption GenerationOption { get; } 20 | } 21 | 22 | /// 23 | /// Define the behaviour of the generated Helper class. All members with a not empty 24 | /// will be mapped 1:1 as long as each member has an unique description. Each option will treat members without a valid 25 | /// differently. 26 | /// 27 | public enum GenerateHelperOption 28 | { 29 | /// 30 | /// Members without description will return null. 31 | /// 32 | IgnoreEnumWithoutDescription = 1, 33 | 34 | /// 35 | /// Members without description will throw an exception when requested. 36 | /// 37 | ThrowForEnumWithoutDescription = 2, 38 | 39 | /// 40 | /// Members without description will be mapped as themselves, equivalent to using nameof() or .ToString(). 41 | /// 42 | UseItselfWhenNoDescription = 3 43 | }"; 44 | 45 | public const string NAMESPACE_TEMPLATE = @"// 46 | using System; 47 | 48 | namespace {namespaceValue} 49 | { 50 | {classTemplate} 51 | }"; 52 | 53 | public const string CLASS_TEMPLATE = @" public static class {enumName}Helper 54 | { 55 | {methodTemplate} 56 | }"; 57 | 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/EnumUtilitiesGenerator/SwitchesBuilder.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | 5 | namespace EnumUtilitiesGenerator 6 | { 7 | internal class SwitchesBuilder 8 | { 9 | private const string DEFAULT_CASE = "_"; 10 | private readonly string _format; 11 | private readonly string _defaultCaseFormat; 12 | private readonly Dictionary _switchCases = new(StringComparer.InvariantCultureIgnoreCase); 13 | private bool _hasDefault; 14 | private (string Default, string Value) _defaultCase; 15 | 16 | public SwitchesBuilder(string format) : this(format, null) 17 | { } 18 | 19 | public SwitchesBuilder(string format, string defaultCaseFormat) 20 | { 21 | _format = format; 22 | _defaultCaseFormat = defaultCaseFormat; 23 | } 24 | 25 | public void Add(string caseValue, string returnValue) 26 | { 27 | if (caseValue == DEFAULT_CASE) 28 | { 29 | if (!_hasDefault) 30 | { 31 | _hasDefault = true; 32 | _defaultCase = (caseValue, returnValue); 33 | return; 34 | } 35 | else 36 | return; 37 | } 38 | 39 | if (_switchCases.TryGetValue(caseValue, out var value) && !value.IsDuplicate) 40 | { 41 | const string exceptionTemplate = "throw new System.InvalidOperationException($\"Multiple members were found with description '{description}'. Could not map description.\")"; 42 | _switchCases[caseValue] = (exceptionTemplate, true); 43 | return; 44 | } 45 | 46 | _switchCases[caseValue] = (returnValue, false); 47 | } 48 | 49 | public string Build(string indentation) 50 | { 51 | var switches = new HashSet(_switchCases.Select(x => string.Format($"{indentation}{_format}", x.Key, x.Value.ReturnValue))); 52 | 53 | if (_hasDefault) 54 | switches.Add($"{indentation}{_defaultCase.Default} => {_defaultCase.Value}"); 55 | 56 | if (_defaultCaseFormat is not null) 57 | switches.Add($"{indentation}{_defaultCaseFormat}"); 58 | 59 | return string.Join(",\r\n", switches); 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /test/Benchmark/Benchmarker.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Attributes; 2 | 3 | namespace Benchmark 4 | { 5 | [MemoryDiagnoser] 6 | public class Benchmarker 7 | { 8 | [Benchmark] 9 | public string ToString_Native_With_5_Members() 10 | { 11 | return FewMembersEnum.Test05.ToString(); 12 | } 13 | 14 | [Benchmark] 15 | public string ToString_Native_With_100_Members() 16 | { 17 | return ManyMembersEnum.Test75.ToString(); 18 | } 19 | 20 | [Benchmark] 21 | public string GetDesriptionFast_Generated_With_5_Members() 22 | { 23 | return FewMembersEnum.Test05.GetDescriptionFast(); 24 | } 25 | 26 | [Benchmark] 27 | public string GetDesriptionFast_Generated_With_100_Members() 28 | { 29 | return ManyMembersEnum.Test75.GetDescriptionFast(); 30 | } 31 | 32 | [Benchmark] 33 | public string GetDesriptionFromEnum_Reflection_With_5_Members() 34 | { 35 | return EnumUtils.GetDescriptionFromEnum(FewMembersEnum.Test05); 36 | } 37 | 38 | [Benchmark] 39 | public string GetDesriptionFromEnum_Reflection_With_100_Members() 40 | { 41 | return EnumUtils.GetDescriptionFromEnum(ManyMembersEnum.Test75); 42 | } 43 | 44 | [Benchmark] 45 | public string GetDesriptionFromEnum_Generator_With_5_Members() 46 | { 47 | return FewMembersEnum.Test05.GetDescriptionFast(); 48 | } 49 | 50 | [Benchmark] 51 | public string GetDesriptionFromEnum_Generator_With_100_Members() 52 | { 53 | return ManyMembersEnum.Test75.GetDescriptionFast(); 54 | } 55 | 56 | [Benchmark] 57 | public FewMembersEnum GetEnumFromDesription_Reflection_With_5_Members() 58 | { 59 | return EnumUtils.GetEnumFromDescription("Teste05"); 60 | } 61 | 62 | [Benchmark] 63 | public ManyMembersEnum GetEnumFromDesription_Reflection_With_100_Members() 64 | { 65 | return EnumUtils.GetEnumFromDescription("Teste75"); 66 | } 67 | 68 | [Benchmark] 69 | public FewMembersEnum? GetEnumFromDesription_Generated_With_5_Members() 70 | { 71 | return FewMembersEnumHelper.GetEnumFromDescriptionFast("Teste05"); 72 | } 73 | 74 | [Benchmark] 75 | public ManyMembersEnum? GetEnumFromDesription_Generated_With_100_Members() 76 | { 77 | return ManyMembersEnumHelper.GetEnumFromDescriptionFast("Teste75"); 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /EnumUtilitiesGenerator.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.32002.261 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EnumUtilitiesGenerator", "src\EnumUtilitiesGenerator\EnumUtilitiesGenerator.csproj", "{5639093D-3D96-465D-8659-D37357B82149}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{DAB25D9D-D3EB-403D-947E-720ACCE1F382}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{E627CD19-21E9-48FD-82AD-4E99AD9B6C11}" 11 | EndProject 12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EnumUtilitiesGenerator.Tests", "test\EnumUtilitiesGenerator.Tests\EnumUtilitiesGenerator.Tests.csproj", "{D64E1BC2-6F92-451A-A8EA-4CDC0EC13B03}" 13 | EndProject 14 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ConsoleApp", "test\ConsoleApp\ConsoleApp.csproj", "{55C4CF12-A6C9-413E-8051-83B36ED2F8A2}" 15 | EndProject 16 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Benchmark", "test\Benchmark\Benchmark.csproj", "{F60CD395-AB9A-469D-90BF-808B17F97244}" 17 | EndProject 18 | Global 19 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 20 | Debug|Any CPU = Debug|Any CPU 21 | Release|Any CPU = Release|Any CPU 22 | EndGlobalSection 23 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 24 | {5639093D-3D96-465D-8659-D37357B82149}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 25 | {5639093D-3D96-465D-8659-D37357B82149}.Debug|Any CPU.Build.0 = Debug|Any CPU 26 | {5639093D-3D96-465D-8659-D37357B82149}.Release|Any CPU.ActiveCfg = Release|Any CPU 27 | {5639093D-3D96-465D-8659-D37357B82149}.Release|Any CPU.Build.0 = Release|Any CPU 28 | {D64E1BC2-6F92-451A-A8EA-4CDC0EC13B03}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 29 | {D64E1BC2-6F92-451A-A8EA-4CDC0EC13B03}.Debug|Any CPU.Build.0 = Debug|Any CPU 30 | {D64E1BC2-6F92-451A-A8EA-4CDC0EC13B03}.Release|Any CPU.ActiveCfg = Release|Any CPU 31 | {D64E1BC2-6F92-451A-A8EA-4CDC0EC13B03}.Release|Any CPU.Build.0 = Release|Any CPU 32 | {55C4CF12-A6C9-413E-8051-83B36ED2F8A2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 33 | {55C4CF12-A6C9-413E-8051-83B36ED2F8A2}.Debug|Any CPU.Build.0 = Debug|Any CPU 34 | {55C4CF12-A6C9-413E-8051-83B36ED2F8A2}.Release|Any CPU.ActiveCfg = Release|Any CPU 35 | {55C4CF12-A6C9-413E-8051-83B36ED2F8A2}.Release|Any CPU.Build.0 = Release|Any CPU 36 | {F60CD395-AB9A-469D-90BF-808B17F97244}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 37 | {F60CD395-AB9A-469D-90BF-808B17F97244}.Debug|Any CPU.Build.0 = Debug|Any CPU 38 | {F60CD395-AB9A-469D-90BF-808B17F97244}.Release|Any CPU.ActiveCfg = Release|Any CPU 39 | {F60CD395-AB9A-469D-90BF-808B17F97244}.Release|Any CPU.Build.0 = Release|Any CPU 40 | EndGlobalSection 41 | GlobalSection(SolutionProperties) = preSolution 42 | HideSolutionNode = FALSE 43 | EndGlobalSection 44 | GlobalSection(NestedProjects) = preSolution 45 | {5639093D-3D96-465D-8659-D37357B82149} = {DAB25D9D-D3EB-403D-947E-720ACCE1F382} 46 | {D64E1BC2-6F92-451A-A8EA-4CDC0EC13B03} = {E627CD19-21E9-48FD-82AD-4E99AD9B6C11} 47 | {55C4CF12-A6C9-413E-8051-83B36ED2F8A2} = {E627CD19-21E9-48FD-82AD-4E99AD9B6C11} 48 | {F60CD395-AB9A-469D-90BF-808B17F97244} = {E627CD19-21E9-48FD-82AD-4E99AD9B6C11} 49 | EndGlobalSection 50 | GlobalSection(ExtensibilityGlobals) = postSolution 51 | SolutionGuid = {735D1D66-C0C4-4C6A-A6A2-128FB01A3184} 52 | EndGlobalSection 53 | EndGlobal 54 | -------------------------------------------------------------------------------- /test/Benchmark/ManyMembersEnum.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | 3 | namespace Benchmark 4 | { 5 | [GenerateHelper(GenerateHelperOption.UseItselfWhenNoDescription)] 6 | public enum ManyMembersEnum 7 | { 8 | [Description("Test00")] Test00, 9 | [Description("Test01")] Test01, 10 | [Description("Test02")] Test02, 11 | [Description("Test03")] Test03, 12 | [Description("Test04")] Test04, 13 | [Description("Test05")] Test05, 14 | [Description("Test06")] Test06, 15 | [Description("Test07")] Test07, 16 | [Description("Test08")] Test08, 17 | [Description("Test09")] Test09, 18 | [Description("Test10")] Test10, 19 | [Description("Test11")] Test11, 20 | [Description("Test12")] Test12, 21 | [Description("Test13")] Test13, 22 | [Description("Test14")] Test14, 23 | [Description("Test15")] Test15, 24 | [Description("Test16")] Test16, 25 | [Description("Test17")] Test17, 26 | [Description("Test18")] Test18, 27 | [Description("Test19")] Test19, 28 | [Description("Test20")] Test20, 29 | [Description("Test21")] Test21, 30 | [Description("Test22")] Test22, 31 | [Description("Test23")] Test23, 32 | [Description("Test24")] Test24, 33 | [Description("Test25")] Test25, 34 | [Description("Test26")] Test26, 35 | [Description("Test27")] Test27, 36 | [Description("Test28")] Test28, 37 | [Description("Test29")] Test29, 38 | [Description("Test30")] Test30, 39 | [Description("Test31")] Test31, 40 | [Description("Test32")] Test32, 41 | [Description("Test33")] Test33, 42 | [Description("Test34")] Test34, 43 | [Description("Test35")] Test35, 44 | [Description("Test36")] Test36, 45 | [Description("Test37")] Test37, 46 | [Description("Test38")] Test38, 47 | [Description("Test39")] Test39, 48 | [Description("Test40")] Test40, 49 | [Description("Test41")] Test41, 50 | [Description("Test42")] Test42, 51 | [Description("Test43")] Test43, 52 | [Description("Test44")] Test44, 53 | [Description("Test45")] Test45, 54 | [Description("Test46")] Test46, 55 | [Description("Test47")] Test47, 56 | [Description("Test48")] Test48, 57 | [Description("Test49")] Test49, 58 | [Description("Test50")] Test50, 59 | [Description("Test51")] Test51, 60 | [Description("Test52")] Test52, 61 | [Description("Test53")] Test53, 62 | [Description("Test54")] Test54, 63 | [Description("Test55")] Test55, 64 | [Description("Test56")] Test56, 65 | [Description("Test57")] Test57, 66 | [Description("Test58")] Test58, 67 | [Description("Test59")] Test59, 68 | [Description("Test60")] Test60, 69 | [Description("Test61")] Test61, 70 | [Description("Test62")] Test62, 71 | [Description("Test63")] Test63, 72 | [Description("Test64")] Test64, 73 | [Description("Test65")] Test65, 74 | [Description("Test66")] Test66, 75 | [Description("Test67")] Test67, 76 | [Description("Test68")] Test68, 77 | [Description("Test69")] Test69, 78 | [Description("Test70")] Test70, 79 | [Description("Test71")] Test71, 80 | [Description("Test72")] Test72, 81 | [Description("Test73")] Test73, 82 | [Description("Test74")] Test74, 83 | [Description("Test75")] Test75, 84 | [Description("Test76")] Test76, 85 | [Description("Test77")] Test77, 86 | [Description("Test78")] Test78, 87 | [Description("Test79")] Test79, 88 | [Description("Test80")] Test80, 89 | [Description("Test81")] Test81, 90 | [Description("Test82")] Test82, 91 | [Description("Test83")] Test83, 92 | [Description("Test84")] Test84, 93 | [Description("Test85")] Test85, 94 | [Description("Test86")] Test86, 95 | [Description("Test87")] Test87, 96 | [Description("Test88")] Test88, 97 | [Description("Test89")] Test89, 98 | [Description("Test90")] Test90, 99 | [Description("Test91")] Test91, 100 | [Description("Test92")] Test92, 101 | [Description("Test93")] Test93, 102 | [Description("Test94")] Test94, 103 | [Description("Test95")] Test95, 104 | [Description("Test96")] Test96, 105 | [Description("Test97")] Test97, 106 | [Description("Test98")] Test98, 107 | [Description("Test99")] Test99, 108 | [Description("Test100")] Test100 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # EnumUtilitiesGenerator 2 | 3 | A source generator for C# that uses Roslyn to create a small helper class for your Enums, with helpfull mapping between an enum member and its description attribute. By using it you avoid using reflection or boilerplate code to map enums and descriptions. 4 | 5 | # Installation 6 | 7 | Install the generator via nuget: 8 | 9 | `Install-Package EnumUtilitiesGenerator -Version 0.1.6` 10 | 11 | # Benchmark 12 | 13 | To prove the performance benefit, some benchmarks were made and compared. Since enums with few and lots of members behave differently, those scenarios were covered. 14 | Scenarios: 15 | - A simple enumMember.ToString() 16 | - Obtaining the DescriptionAttribute value 17 | - Obtaining the enum from a given DescriptionAttribute value 18 | 19 | ## Results: 20 | ``` 21 | | Method | Mean | Error | StdDev | Median | Gen 0 | Gen 1 | Allocated | 22 | |-------------------------------------------------- |---------------:|--------------:|--------------:|---------------:|-------:|-------:|----------:| 23 | | ToString_Native_With_5_Members | 77.695 ns | 7.4842 ns | 22.0672 ns | 85.540 ns | 0.0057 | - | 24 B | 24 | | GetDesriptionFast_Generated_With_5_Members | 2.099 ns | 0.1701 ns | 0.4824 ns | 2.297 ns | - | - | - | 25 | | ToString_Native_With_100_Members | 28.546 ns | 0.5210 ns | 0.8847 ns | 28.761 ns | 0.0057 | 0.0003 | 24 B | 26 | | GetDesriptionFast_Generated_With_100_Members | 2.434 ns | 0.0725 ns | 0.0566 ns | 2.433 ns | - | - | - | 27 | | GetDesriptionFromEnum_Reflection_With_5_Members | 1,327.510 ns | 10.4239 ns | 9.2405 ns | 1,329.483 ns | 0.0610 | - | 256 B | 28 | | GetDesriptionFromEnum_Generator_With_5_Members | 2.034 ns | 0.1203 ns | 0.2260 ns | 2.064 ns | - | - | - | 29 | | GetDesriptionFromEnum_Reflection_With_100_Members | 1,381.913 ns | 27.5457 ns | 72.0823 ns | 1,392.869 ns | 0.0610 | - | 256 B | 30 | | GetDesriptionFromEnum_Generator_With_100_Members | 2.617 ns | 0.0500 ns | 0.0443 ns | 2.616 ns | - | - | - | 31 | | GetEnumFromDesription_Reflection_With_5_Members | 8,545.634 ns | 140.6773 ns | 162.0042 ns | 8,483.183 ns | 0.3510 | - | 1,496 B | 32 | | GetEnumFromDesription_Generated_With_5_Members | 320.504 ns | 4.4171 ns | 3.9157 ns | 321.430 ns | - | - | - | 33 | | GetEnumFromDesription_Reflection_With_100_Members | 105,295.058 ns | 2,094.0809 ns | 5,176.0491 ns | 106,267.151 ns | 4.3945 | - | 18,498 B | 34 | | GetEnumFromDesription_Generated_With_100_Members | 4,749.037 ns | 66.6945 ns | 62.3861 ns | 4,729.669 ns | - | - | - | 35 | ``` 36 | 37 | It's very clear how the generated code is faster and also does not pressure the garbage collector. 38 | 39 | # How to use it 40 | 41 | Add the attribute GenerateHelper to the enums you want to map members and descriptions, like so: 42 | 43 | ```csharp 44 | [GenerateHelper(GenerateHelperOption.UseItselfWhenNoDescription)] 45 | public enum PaymentMethod 46 | { 47 | [Description("Credit card")] 48 | Credit, 49 | [Description("Debit card")] 50 | Debit, 51 | Cash 52 | } 53 | ``` 54 | 55 | That will generate a helper class with 2 methods with compile-time mapping, for each enum found in the consuming project with the GenerateHelper attribute, and an extra method to return all available descriptions. 56 | 57 | The generated code: 58 | 59 | ```csharp 60 | public static class PaymentMethodHelper 61 | { 62 | private static readonly string[] _descriptions = new string[] 63 | { 64 | "Credit card", 65 | "Debit card", 66 | }; 67 | 68 | public static string[] GetAvailableDescriptions() 69 | { 70 | return _descriptions; 71 | } 72 | 73 | public static string GetDescriptionFast(this PaymentMethod @enum) 74 | { 75 | return @enum switch 76 | { 77 | PaymentMethod.Credit => "Credit card", 78 | PaymentMethod.Debit => "Debit card", 79 | PaymentMethod.Cash => nameof(PaymentMethod.Cash) 80 | }; 81 | } 82 | 83 | public static PaymentMethod? GetEnumFromDescriptionFast(string description) 84 | { 85 | return GetEnumFromDescriptionFast(description, StringComparison.InvariantCultureIgnoreCase); 86 | } 87 | 88 | public static PaymentMethod? GetEnumFromDescriptionFast(string description, StringComparison stringComparison) 89 | { 90 | return description switch 91 | { 92 | _ when string.Equals("Credit card", description, stringComparison) => PaymentMethod.Credit, 93 | _ when string.Equals("Debit card", description, stringComparison) => PaymentMethod.Debit, 94 | _ when string.Equals("Cash", description, stringComparison) => PaymentMethod.Cash, 95 | _ => null 96 | }; 97 | } 98 | } 99 | ``` 100 | 101 | # Behaviour 102 | 103 | Each member will be mapped to and from its Description value. Members without the attribute or with an empty attribute will map according to the option chosen: 104 | 105 | - IgnoreEnumWithoutDescription: Returns null 106 | - ThrowForEnumWithoutDescription: throws an InvalidOperationException. 107 | - UseItselfWhenNoDescription: will map using the member name. Equivalent to nameof(EnumType.MemberX) or EnumType.MemberX.ToString(). 108 | 109 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Oo]ut/ 33 | [Ll]og/ 34 | [Ll]ogs/ 35 | 36 | # Visual Studio 2015/2017 cache/options directory 37 | .vs/ 38 | # Uncomment if you have tasks that create the project's static files in wwwroot 39 | #wwwroot/ 40 | 41 | # Visual Studio 2017 auto generated files 42 | Generated\ Files/ 43 | 44 | # MSTest test Results 45 | [Tt]est[Rr]esult*/ 46 | [Bb]uild[Ll]og.* 47 | 48 | # NUnit 49 | *.VisualState.xml 50 | TestResult.xml 51 | nunit-*.xml 52 | 53 | # Build Results of an ATL Project 54 | [Dd]ebugPS/ 55 | [Rr]eleasePS/ 56 | dlldata.c 57 | 58 | # Benchmark Results 59 | BenchmarkDotNet.Artifacts/ 60 | 61 | # .NET Core 62 | project.lock.json 63 | project.fragment.lock.json 64 | artifacts/ 65 | 66 | # ASP.NET Scaffolding 67 | ScaffoldingReadMe.txt 68 | 69 | # StyleCop 70 | StyleCopReport.xml 71 | 72 | # Files built by Visual Studio 73 | *_i.c 74 | *_p.c 75 | *_h.h 76 | *.ilk 77 | *.meta 78 | *.obj 79 | *.iobj 80 | *.pch 81 | *.pdb 82 | *.ipdb 83 | *.pgc 84 | *.pgd 85 | *.rsp 86 | *.sbr 87 | *.tlb 88 | *.tli 89 | *.tlh 90 | *.tmp 91 | *.tmp_proj 92 | *_wpftmp.csproj 93 | *.log 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio LightSwitch build output 298 | **/*.HTMLClient/GeneratedArtifacts 299 | **/*.DesktopClient/GeneratedArtifacts 300 | **/*.DesktopClient/ModelManifest.xml 301 | **/*.Server/GeneratedArtifacts 302 | **/*.Server/ModelManifest.xml 303 | _Pvt_Extensions 304 | 305 | # Paket dependency manager 306 | .paket/paket.exe 307 | paket-files/ 308 | 309 | # FAKE - F# Make 310 | .fake/ 311 | 312 | # CodeRush personal settings 313 | .cr/personal 314 | 315 | # Python Tools for Visual Studio (PTVS) 316 | __pycache__/ 317 | *.pyc 318 | 319 | # Cake - Uncomment if you are using it 320 | # tools/** 321 | # !tools/packages.config 322 | 323 | # Tabs Studio 324 | *.tss 325 | 326 | # Telerik's JustMock configuration file 327 | *.jmconfig 328 | 329 | # BizTalk build output 330 | *.btp.cs 331 | *.btm.cs 332 | *.odx.cs 333 | *.xsd.cs 334 | 335 | # OpenCover UI analysis results 336 | OpenCover/ 337 | 338 | # Azure Stream Analytics local run output 339 | ASALocalRun/ 340 | 341 | # MSBuild Binary and Structured Log 342 | *.binlog 343 | 344 | # NVidia Nsight GPU debugger configuration file 345 | *.nvuser 346 | 347 | # MFractors (Xamarin productivity tool) working folder 348 | .mfractor/ 349 | 350 | # Local History for Visual Studio 351 | .localhistory/ 352 | 353 | # BeatPulse healthcheck temp database 354 | healthchecksdb 355 | 356 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 357 | MigrationBackup/ 358 | 359 | # Ionide (cross platform F# VS Code tools) working folder 360 | .ionide/ 361 | 362 | # Fody - auto-generated XML schema 363 | FodyWeavers.xsd -------------------------------------------------------------------------------- /src/EnumUtilitiesGenerator/EnumHelperGenerator.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.CodeAnalysis; 2 | using Microsoft.CodeAnalysis.CSharp; 3 | using Microsoft.CodeAnalysis.Text; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Text; 8 | 9 | namespace EnumUtilitiesGenerator 10 | { 11 | [Generator] 12 | public class EnumHelperGenerator : ISourceGenerator 13 | { 14 | private enum GenerateExtensionOption 15 | { 16 | IgnoreEnumWithoutDescription = 1, 17 | ThrowForEnumWithoutDescription = 2, 18 | UseItselfWhenNoDescription = 3 19 | } 20 | 21 | public void Initialize(GeneratorInitializationContext context) 22 | { 23 | context.RegisterForPostInitialization(c => c.AddSource("GenerateHelper.g.cs", SourceText.From(Constants.GENERATEHELPER_ATTRIBUTE, Encoding.UTF8))); 24 | context.RegisterForSyntaxNotifications(() => new ServicesReceiver()); 25 | } 26 | 27 | public void Execute(GeneratorExecutionContext context) 28 | { 29 | var receiver = (ServicesReceiver?)context.SyntaxReceiver; 30 | if (receiver == null || !receiver.EnumsToGenerate.Any()) 31 | return; 32 | 33 | try 34 | { 35 | foreach (var @enum in receiver.EnumsToGenerate) 36 | { 37 | var semanticModel = context.Compilation.GetSemanticModel(@enum.SyntaxTree); 38 | if (semanticModel == null) 39 | continue; 40 | 41 | ISymbol? symbol = semanticModel.GetDeclaredSymbol(@enum); 42 | if (symbol == null) 43 | return; 44 | 45 | AttributeData? generateAttribute = symbol.GetAttributes() 46 | .FirstOrDefault(at => at.AttributeClass?.Name == Constants.GENERATEHELPER_FULL_NAME || at.AttributeClass?.Name == Constants.GENERATEHELPER_NAME); 47 | 48 | if (generateAttribute is null || generateAttribute.ConstructorArguments.IsEmpty) 49 | continue; 50 | 51 | var args = generateAttribute.ConstructorArguments[0]; 52 | var generationBehavior = (GenerateExtensionOption)(int)args.Value!; 53 | 54 | ISymbol[] membersSymbols = new ISymbol[@enum.Members.Count]; 55 | for (int i = 0; i < @enum.Members.Count; i++) 56 | membersSymbols[i] = semanticModel.GetDeclaredSymbol(@enum.Members[i])!; 57 | 58 | var methodBuilder = new StringBuilder(); 59 | 60 | GenerateMethods(methodBuilder, membersSymbols, generationBehavior); 61 | methodBuilder.Replace("{enumType}", symbol.Name); 62 | 63 | string methodsGenerated = methodBuilder.ToString(); 64 | 65 | string generatedClass = Constants.CLASS_TEMPLATE 66 | .Replace("{enumName}", symbol.Name) 67 | .Replace("{methodTemplate}", methodsGenerated); 68 | 69 | string source = Constants.NAMESPACE_TEMPLATE 70 | .Replace("{namespaceValue}", symbol.ContainingNamespace.ToDisplayString()) 71 | .Replace("{classTemplate}", generatedClass); 72 | 73 | context.AddSource($"{symbol.Name}Helper.g.cs", SourceText.From(source, Encoding.UTF8)); 74 | } 75 | } 76 | catch (Exception) 77 | { 78 | // do not generate 79 | } 80 | } 81 | 82 | private void GenerateMethods(StringBuilder methodBuilder, ISymbol[] membersSymbols, GenerateExtensionOption option) 83 | { 84 | var descList = new HashSet(); 85 | var getDescFastBodyBuilder = new SwitchesBuilder("{0} => {1}"); 86 | 87 | const string switchFormat = "_ when string.Equals({0}, description, stringComparison) => {1}"; 88 | SwitchesBuilder getEnumFromDescFastBodyBuilder = option switch 89 | { 90 | GenerateExtensionOption.UseItselfWhenNoDescription => new SwitchesBuilder(switchFormat, "_ => null"), 91 | GenerateExtensionOption.IgnoreEnumWithoutDescription => new SwitchesBuilder(switchFormat, "_ => null"), 92 | GenerateExtensionOption.ThrowForEnumWithoutDescription => new SwitchesBuilder(switchFormat, "_ => throw new System.InvalidOperationException($\"Enum for description '{description}' was not found.\")"), 93 | }; 94 | 95 | foreach (var item in membersSymbols) 96 | { 97 | AttributeData? descriptionAttribute = item.GetAttributes().FirstOrDefault(at => at.AttributeClass!.ToString() == "System.ComponentModel.DescriptionAttribute"); 98 | 99 | IterateGetAvailableDescriptions(descList, descriptionAttribute); 100 | IterateGetDescriptionFast(getDescFastBodyBuilder, descriptionAttribute, item, option); 101 | IterateGetEnumFromDescriptionFast(getEnumFromDescFastBodyBuilder, descriptionAttribute, item, option); 102 | } 103 | 104 | BuildGetAvailableDescriptionsMethod(methodBuilder, descList); 105 | BuildGetDescriptionFastMethod(methodBuilder, getDescFastBodyBuilder); 106 | BuildGetEnumFromDescriptionFastMethod(methodBuilder, option, getEnumFromDescFastBodyBuilder); 107 | } 108 | 109 | private static void BuildGetAvailableDescriptionsMethod(StringBuilder methodBuilder, HashSet descList) 110 | { 111 | var methodTemplate = @" private static readonly string[] _descriptions = new string[] 112 | { 113 | {listTemplate} 114 | }; 115 | 116 | /// 117 | /// Get an array of all the descriptions available. Members without or with empty 118 | /// will not be included, not even as themselves. 119 | /// 120 | public static string[] GetAvailableDescriptions() 121 | { 122 | return _descriptions; 123 | } 124 | "; 125 | 126 | methodBuilder.AppendLine(methodTemplate.Replace("{listTemplate}", string.Join("\r\n", descList))); 127 | } 128 | 129 | private static void BuildGetDescriptionFastMethod(StringBuilder methodBuilder, SwitchesBuilder switchesBuilder) 130 | { 131 | var switchesBodyGetDescFast = switchesBuilder.Build(Indent(4)); 132 | methodBuilder.AppendLine(@" public static string GetDescriptionFast(this {enumType} @enum) 133 | { 134 | #pragma warning disable CS8524 // The switch expression does not handle some values of its input type (it is not exhaustive) involving an unnamed enum value. 135 | return @enum switch 136 | #pragma warning restore CS8524 // The switch expression does not handle some values of its input type (it is not exhaustive) involving an unnamed enum value. 137 | { 138 | {switchTemplate} 139 | }; 140 | } 141 | ".Replace("{switchTemplate}", switchesBodyGetDescFast)); 142 | } 143 | 144 | private static void BuildGetEnumFromDescriptionFastMethod(StringBuilder methodBuilder, GenerateExtensionOption option, SwitchesBuilder switchesBuilder) 145 | { 146 | var switchesBodyGetEnumFromDescFast = switchesBuilder.Build(Indent(4)); 147 | 148 | GetGetEnumFromDescriptionDoc(methodBuilder, option, true); 149 | methodBuilder.AppendLine(@" public static {enumType}? GetEnumFromDescriptionFast(string description) 150 | { 151 | return GetEnumFromDescriptionFast(description, StringComparison.InvariantCultureIgnoreCase); 152 | } 153 | "); 154 | 155 | GetGetEnumFromDescriptionDoc(methodBuilder, option, false); 156 | methodBuilder.AppendLine(@" public static {enumType}? GetEnumFromDescriptionFast(string description, StringComparison stringComparison) 157 | { 158 | #pragma warning disable CS8509 // The switch expression does not handle all possible values of its input type (it is not exhaustive). 159 | return description switch 160 | #pragma warning restore CS8509 // The switch expression does not handle all possible values of its input type (it is not exhaustive). 161 | { 162 | {switchTemplate} 163 | }; 164 | }".Replace("{switchTemplate}", switchesBodyGetEnumFromDescFast)); 165 | } 166 | 167 | private static void IterateGetAvailableDescriptions(HashSet descsList, AttributeData? descriptionAttribute) 168 | { 169 | if (descriptionAttribute is null || descriptionAttribute.ConstructorArguments.IsEmpty) 170 | return; 171 | 172 | string value = ((string)descriptionAttribute!.ConstructorArguments[0].Value!).Quote(); 173 | 174 | descsList.Add(Indent(3) + value + ","); 175 | } 176 | 177 | private static void IterateGetDescriptionFast(SwitchesBuilder builder, AttributeData? descriptionAttribute, ISymbol enumMember, GenerateExtensionOption option) 178 | { 179 | Func getAttrValue = () => (string)descriptionAttribute!.ConstructorArguments[0].Value!; 180 | 181 | string exceptionTemplate = $"throw new System.InvalidOperationException(\"Description for member {enumMember.Name} was not found.\")"; 182 | 183 | (string enumValue, string description) = (descriptionAttribute, option) switch 184 | { 185 | (null, GenerateExtensionOption.IgnoreEnumWithoutDescription) => ("_", "null"), 186 | (null, GenerateExtensionOption.ThrowForEnumWithoutDescription) => ($"{{enumType}}.{enumMember.Name}", exceptionTemplate), 187 | (null, GenerateExtensionOption.UseItselfWhenNoDescription) => ($"{{enumType}}.{enumMember.Name}", $"nameof({{enumType}}.{enumMember.Name})"), 188 | 189 | (not null, GenerateExtensionOption.IgnoreEnumWithoutDescription) when descriptionAttribute.ConstructorArguments.Length == 0 => ("_", "null"), 190 | (not null, GenerateExtensionOption.ThrowForEnumWithoutDescription) when descriptionAttribute.ConstructorArguments.Length == 0 => ($"{{enumType}}.{enumMember.Name}", exceptionTemplate), 191 | (not null, GenerateExtensionOption.UseItselfWhenNoDescription) when descriptionAttribute.ConstructorArguments.Length == 0 => ($"{{enumType}}.{enumMember.Name}", $"nameof({{enumType}}.{enumMember.Name})"), 192 | 193 | (not null, _) => ($"{{enumType}}.{enumMember.Name}", getAttrValue().Quote()) 194 | }; 195 | 196 | builder.Add(enumValue, description); 197 | } 198 | 199 | private static void IterateGetEnumFromDescriptionFast(SwitchesBuilder builder, AttributeData? descriptionAttribute, ISymbol enumMember, GenerateExtensionOption option) 200 | { 201 | Func getAttrValue = () => (string)descriptionAttribute!.ConstructorArguments[0].Value!; 202 | const string exceptionTemplate = "throw new System.InvalidOperationException($\"Enum for description '{description}' was not found.\")"; 203 | 204 | (string description, string value) = (descriptionAttribute, option) switch 205 | { 206 | (null, GenerateExtensionOption.IgnoreEnumWithoutDescription) => ("_", "null"), 207 | (null, GenerateExtensionOption.ThrowForEnumWithoutDescription) => ("_", exceptionTemplate), 208 | (null, GenerateExtensionOption.UseItselfWhenNoDescription) => (enumMember.Name.Quote(), $"{{enumType}}.{enumMember.Name}"), 209 | 210 | (not null, GenerateExtensionOption.IgnoreEnumWithoutDescription) when descriptionAttribute.ConstructorArguments.Length == 0 => ("_", "null"), 211 | (not null, GenerateExtensionOption.ThrowForEnumWithoutDescription) when descriptionAttribute.ConstructorArguments.Length == 0 => ("_", exceptionTemplate), 212 | (not null, GenerateExtensionOption.UseItselfWhenNoDescription) when descriptionAttribute.ConstructorArguments.Length == 0 => (enumMember.Name.Quote(), $"{{enumType}}.{enumMember.Name}"), 213 | 214 | (not null, _) => (getAttrValue().Quote(), $"{{enumType}}.{enumMember.Name}"), 215 | }; 216 | 217 | builder.Add(description, value); 218 | } 219 | 220 | private static void GetGetEnumFromDescriptionDoc(StringBuilder methodBuilder, GenerateExtensionOption generateExtensionOption, bool isDefault) 221 | { 222 | const int indentLevel = 2; 223 | methodBuilder.AppendLine(Indent(indentLevel) + "/// "); 224 | 225 | var doc = isDefault ? $@"/// Returns the enum that has the given description. Compares using ." 226 | : $@"/// Returns the enum that has the given description using any ."; 227 | 228 | methodBuilder.AppendLine(Indent(indentLevel) + doc); 229 | 230 | if (generateExtensionOption == GenerateExtensionOption.IgnoreEnumWithoutDescription) 231 | methodBuilder.AppendLine(Indent(indentLevel) + "/// Returns null if no enum with given description was found."); 232 | else if (generateExtensionOption == GenerateExtensionOption.ThrowForEnumWithoutDescription) 233 | methodBuilder.AppendLine(Indent(indentLevel) + @"/// Throws if no enum with given description was found."); 234 | 235 | methodBuilder.AppendLine(Indent(indentLevel) + "/// "); 236 | methodBuilder.AppendLine(Indent(indentLevel) + @"/// The value"); 237 | } 238 | 239 | private static string Indent(int n) 240 | { 241 | return new string(' ', 4 * n); 242 | } 243 | } 244 | } 245 | --------------------------------------------------------------------------------