├── .github └── FUNDING.yml ├── .gitignore ├── EnumerationClassGenerator.Sample ├── CardType.cs ├── EnumerationClassGenerator.Sample.csproj └── Program.cs ├── EnumerationClassGenerator.sln ├── EnumerationClassGenerator ├── Enumeration.cs ├── EnumerationClassGenerator.csproj ├── Generator.cs ├── GeneratorConstants.cs └── SyntaxReceiver.cs ├── LICENSE └── README.md /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: HamedFathi 4 | patreon: # Replace with a single Patreon username 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry 13 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] 14 | -------------------------------------------------------------------------------- /.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 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | [Ll]ogs/ 33 | 34 | # Visual Studio 2015/2017 cache/options directory 35 | .vs/ 36 | # Uncomment if you have tasks that create the project's static files in wwwroot 37 | #wwwroot/ 38 | 39 | # Visual Studio 2017 auto generated files 40 | Generated\ Files/ 41 | 42 | # MSTest test Results 43 | [Tt]est[Rr]esult*/ 44 | [Bb]uild[Ll]og.* 45 | 46 | # NUnit 47 | *.VisualState.xml 48 | TestResult.xml 49 | nunit-*.xml 50 | 51 | # Build Results of an ATL Project 52 | [Dd]ebugPS/ 53 | [Rr]eleasePS/ 54 | dlldata.c 55 | 56 | # Benchmark Results 57 | BenchmarkDotNet.Artifacts/ 58 | 59 | # .NET Core 60 | project.lock.json 61 | project.fragment.lock.json 62 | artifacts/ 63 | 64 | # StyleCop 65 | StyleCopReport.xml 66 | 67 | # Files built by Visual Studio 68 | *_i.c 69 | *_p.c 70 | *_h.h 71 | *.ilk 72 | *.meta 73 | *.obj 74 | *.iobj 75 | *.pch 76 | *.pdb 77 | *.ipdb 78 | *.pgc 79 | *.pgd 80 | *.rsp 81 | *.sbr 82 | *.tlb 83 | *.tli 84 | *.tlh 85 | *.tmp 86 | *.tmp_proj 87 | *_wpftmp.csproj 88 | *.log 89 | *.vspscc 90 | *.vssscc 91 | .builds 92 | *.pidb 93 | *.svclog 94 | *.scc 95 | 96 | # Chutzpah Test files 97 | _Chutzpah* 98 | 99 | # Visual C++ cache files 100 | ipch/ 101 | *.aps 102 | *.ncb 103 | *.opendb 104 | *.opensdf 105 | *.sdf 106 | *.cachefile 107 | *.VC.db 108 | *.VC.VC.opendb 109 | 110 | # Visual Studio profiler 111 | *.psess 112 | *.vsp 113 | *.vspx 114 | *.sap 115 | 116 | # Visual Studio Trace Files 117 | *.e2e 118 | 119 | # TFS 2012 Local Workspace 120 | $tf/ 121 | 122 | # Guidance Automation Toolkit 123 | *.gpState 124 | 125 | # ReSharper is a .NET coding add-in 126 | _ReSharper*/ 127 | *.[Rr]e[Ss]harper 128 | *.DotSettings.user 129 | 130 | # TeamCity is a build add-in 131 | _TeamCity* 132 | 133 | # DotCover is a Code Coverage Tool 134 | *.dotCover 135 | 136 | # AxoCover is a Code Coverage Tool 137 | .axoCover/* 138 | !.axoCover/settings.json 139 | 140 | # Visual Studio code coverage results 141 | *.coverage 142 | *.coveragexml 143 | 144 | # NCrunch 145 | _NCrunch_* 146 | .*crunch*.local.xml 147 | nCrunchTemp_* 148 | 149 | # MightyMoose 150 | *.mm.* 151 | AutoTest.Net/ 152 | 153 | # Web workbench (sass) 154 | .sass-cache/ 155 | 156 | # Installshield output folder 157 | [Ee]xpress/ 158 | 159 | # DocProject is a documentation generator add-in 160 | DocProject/buildhelp/ 161 | DocProject/Help/*.HxT 162 | DocProject/Help/*.HxC 163 | DocProject/Help/*.hhc 164 | DocProject/Help/*.hhk 165 | DocProject/Help/*.hhp 166 | DocProject/Help/Html2 167 | DocProject/Help/html 168 | 169 | # Click-Once directory 170 | publish/ 171 | 172 | # Publish Web Output 173 | *.[Pp]ublish.xml 174 | *.azurePubxml 175 | # Note: Comment the next line if you want to checkin your web deploy settings, 176 | # but database connection strings (with potential passwords) will be unencrypted 177 | *.pubxml 178 | *.publishproj 179 | 180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 181 | # checkin your Azure Web App publish settings, but sensitive information contained 182 | # in these scripts will be unencrypted 183 | PublishScripts/ 184 | 185 | # NuGet Packages 186 | *.nupkg 187 | # NuGet Symbol Packages 188 | *.snupkg 189 | # The packages folder can be ignored because of Package Restore 190 | **/[Pp]ackages/* 191 | # except build/, which is used as an MSBuild target. 192 | !**/[Pp]ackages/build/ 193 | # Uncomment if necessary however generally it will be regenerated when needed 194 | #!**/[Pp]ackages/repositories.config 195 | # NuGet v3's project.json files produces more ignorable files 196 | *.nuget.props 197 | *.nuget.targets 198 | 199 | # Microsoft Azure Build Output 200 | csx/ 201 | *.build.csdef 202 | 203 | # Microsoft Azure Emulator 204 | ecf/ 205 | rcf/ 206 | 207 | # Windows Store app package directories and files 208 | AppPackages/ 209 | BundleArtifacts/ 210 | Package.StoreAssociation.xml 211 | _pkginfo.txt 212 | *.appx 213 | *.appxbundle 214 | *.appxupload 215 | 216 | # Visual Studio cache files 217 | # files ending in .cache can be ignored 218 | *.[Cc]ache 219 | # but keep track of directories ending in .cache 220 | !?*.[Cc]ache/ 221 | 222 | # Others 223 | ClientBin/ 224 | ~$* 225 | *~ 226 | *.dbmdl 227 | *.dbproj.schemaview 228 | *.jfm 229 | *.pfx 230 | *.publishsettings 231 | orleans.codegen.cs 232 | 233 | # Including strong name files can present a security risk 234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 235 | #*.snk 236 | 237 | # Since there are multiple workflows, uncomment next line to ignore bower_components 238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 239 | #bower_components/ 240 | 241 | # RIA/Silverlight projects 242 | Generated_Code/ 243 | 244 | # Backup & report files from converting an old project file 245 | # to a newer Visual Studio version. Backup files are not needed, 246 | # because we have git ;-) 247 | _UpgradeReport_Files/ 248 | Backup*/ 249 | UpgradeLog*.XML 250 | UpgradeLog*.htm 251 | ServiceFabricBackup/ 252 | *.rptproj.bak 253 | 254 | # SQL Server files 255 | *.mdf 256 | *.ldf 257 | *.ndf 258 | 259 | # Business Intelligence projects 260 | *.rdl.data 261 | *.bim.layout 262 | *.bim_*.settings 263 | *.rptproj.rsuser 264 | *- [Bb]ackup.rdl 265 | *- [Bb]ackup ([0-9]).rdl 266 | *- [Bb]ackup ([0-9][0-9]).rdl 267 | 268 | # Microsoft Fakes 269 | FakesAssemblies/ 270 | 271 | # GhostDoc plugin setting file 272 | *.GhostDoc.xml 273 | 274 | # Node.js Tools for Visual Studio 275 | .ntvs_analysis.dat 276 | node_modules/ 277 | 278 | # Visual Studio 6 build log 279 | *.plg 280 | 281 | # Visual Studio 6 workspace options file 282 | *.opt 283 | 284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 285 | *.vbw 286 | 287 | # Visual Studio LightSwitch build output 288 | **/*.HTMLClient/GeneratedArtifacts 289 | **/*.DesktopClient/GeneratedArtifacts 290 | **/*.DesktopClient/ModelManifest.xml 291 | **/*.Server/GeneratedArtifacts 292 | **/*.Server/ModelManifest.xml 293 | _Pvt_Extensions 294 | 295 | # Paket dependency manager 296 | .paket/paket.exe 297 | paket-files/ 298 | 299 | # FAKE - F# Make 300 | .fake/ 301 | 302 | # CodeRush personal settings 303 | .cr/personal 304 | 305 | # Python Tools for Visual Studio (PTVS) 306 | __pycache__/ 307 | *.pyc 308 | 309 | # Cake - Uncomment if you are using it 310 | # tools/** 311 | # !tools/packages.config 312 | 313 | # Tabs Studio 314 | *.tss 315 | 316 | # Telerik's JustMock configuration file 317 | *.jmconfig 318 | 319 | # BizTalk build output 320 | *.btp.cs 321 | *.btm.cs 322 | *.odx.cs 323 | *.xsd.cs 324 | 325 | # OpenCover UI analysis results 326 | OpenCover/ 327 | 328 | # Azure Stream Analytics local run output 329 | ASALocalRun/ 330 | 331 | # MSBuild Binary and Structured Log 332 | *.binlog 333 | 334 | # NVidia Nsight GPU debugger configuration file 335 | *.nvuser 336 | 337 | # MFractors (Xamarin productivity tool) working folder 338 | .mfractor/ 339 | 340 | # Local History for Visual Studio 341 | .localhistory/ 342 | 343 | # BeatPulse healthcheck temp database 344 | healthchecksdb 345 | 346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 347 | MigrationBackup/ 348 | 349 | # Ionide (cross platform F# VS Code tools) working folder 350 | .ionide/ 351 | -------------------------------------------------------------------------------- /EnumerationClassGenerator.Sample/CardType.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | 4 | namespace EnumerationClassGenerator.Sample 5 | { 6 | [EnumerationClass(/*"MyClass", "MyNamespace"*/)] 7 | public enum CardType 8 | { 9 | Amex, 10 | Visa, 11 | MasterCard 12 | } 13 | 14 | public partial class CardTypeEnumeration 15 | { 16 | public void MyNewMethod() 17 | { 18 | 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /EnumerationClassGenerator.Sample/EnumerationClassGenerator.Sample.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netstandard2.0 5 | 6 | 7 | 8 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /EnumerationClassGenerator.Sample/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace EnumerationClassGenerator.Sample 4 | { 5 | internal class Program 6 | { 7 | static void Main(string[] args) 8 | { 9 | Console.WriteLine("Hello World!"); 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /EnumerationClassGenerator.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.0.31903.59 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EnumerationClassGenerator", "EnumerationClassGenerator\EnumerationClassGenerator.csproj", "{B03B1388-2D74-4733-BC29-E392D36D367B}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EnumerationClassGenerator.Sample", "EnumerationClassGenerator.Sample\EnumerationClassGenerator.Sample.csproj", "{0E532D3C-04DE-4BC3-92BD-9664EB19108E}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {B03B1388-2D74-4733-BC29-E392D36D367B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {B03B1388-2D74-4733-BC29-E392D36D367B}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {B03B1388-2D74-4733-BC29-E392D36D367B}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {B03B1388-2D74-4733-BC29-E392D36D367B}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {0E532D3C-04DE-4BC3-92BD-9664EB19108E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {0E532D3C-04DE-4BC3-92BD-9664EB19108E}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {0E532D3C-04DE-4BC3-92BD-9664EB19108E}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {0E532D3C-04DE-4BC3-92BD-9664EB19108E}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | GlobalSection(ExtensibilityGlobals) = postSolution 29 | SolutionGuid = {C2249FB8-0519-49B4-A588-BF39706337B4} 30 | EndGlobalSection 31 | EndGlobal 32 | -------------------------------------------------------------------------------- /EnumerationClassGenerator/Enumeration.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Reflection; 5 | 6 | namespace EnumerationClassGenerator 7 | { 8 | public abstract class Enumeration : IComparable 9 | { 10 | public int Id { get; } 11 | public string Name { get;} 12 | 13 | protected Enumeration(int id, string name) 14 | { 15 | Id = id; 16 | Name = name; 17 | } 18 | 19 | public override string ToString() => Name; 20 | 21 | public static IEnumerable GetAll() where T : Enumeration 22 | { 23 | var fields = typeof(T).GetFields(BindingFlags.Public | 24 | BindingFlags.Static | 25 | BindingFlags.DeclaredOnly); 26 | 27 | return fields.Select(f => f.GetValue(null)).Cast(); 28 | } 29 | 30 | public override bool Equals(object obj) 31 | { 32 | var otherValue = obj as Enumeration; 33 | 34 | if (otherValue == null) 35 | return false; 36 | 37 | var typeMatches = GetType() == obj.GetType(); 38 | var valueMatches = Id.Equals(otherValue.Id); 39 | 40 | return typeMatches && valueMatches; 41 | } 42 | 43 | public override int GetHashCode() => Id.GetHashCode(); 44 | 45 | public static int AbsoluteDifference(Enumeration firstValue, Enumeration secondValue) 46 | { 47 | return Math.Abs(firstValue.Id - secondValue.Id); 48 | } 49 | 50 | public static T FromValue(int value) where T : Enumeration 51 | { 52 | return Parse(value, "value", item => item.Id == value); 53 | } 54 | 55 | public static T FromDisplayName(string displayName) where T : Enumeration 56 | { 57 | return Parse(displayName, "display name", item => item.Name == displayName); 58 | } 59 | 60 | private static T Parse(K value, string description, Func predicate) where T : Enumeration 61 | { 62 | var matchingItem = GetAll().FirstOrDefault(predicate); 63 | 64 | if (matchingItem == null) 65 | throw new InvalidOperationException($"'{value}' is not a valid {description} in {typeof(T)}"); 66 | 67 | return matchingItem; 68 | } 69 | 70 | private static bool TryParse(K value, string description, Func predicate, out T result) where T : Enumeration 71 | { 72 | var matchingItem = GetAll().FirstOrDefault(predicate); 73 | 74 | result = matchingItem; 75 | 76 | return matchingItem != null; 77 | } 78 | 79 | public int CompareTo(object other) => Id.CompareTo(((Enumeration) other).Id); 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /EnumerationClassGenerator/EnumerationClassGenerator.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | netstandard2.0 4 | 0.0.3 5 | EnumerationClassGenerator 6 | latest 7 | true 8 | false 9 | Hamed Fathi 10 | A C# source generator to create an enumeration class from an enum type. 11 | N/A 12 | https://github.com/HamedFathi/EnumerationClassGenerator 13 | Copyright 2021 - Hamed Fathi 14 | false 15 | MIT 16 | dotnet 17 | true 18 | true 19 | true 20 | $(BaseIntermediateOutputPath)Generated 21 | 22 | 23 | https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet5/nuget/v3/index.json ;$(RestoreAdditionalProjectSources) 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | all 37 | runtime; build; native; contentfiles; analyzers; buildtransitive 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /EnumerationClassGenerator/Generator.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.CodeAnalysis; 2 | using Microsoft.CodeAnalysis.CSharp; 3 | using Microsoft.CodeAnalysis.Text; 4 | using System.Linq; 5 | using System.Text; 6 | 7 | namespace EnumerationClassGenerator 8 | { 9 | [Generator] 10 | public class Generator : ISourceGenerator 11 | { 12 | public void Execute(GeneratorExecutionContext context) 13 | { 14 | context.AddSource(nameof(GeneratorConstants.EnumerationClass), SourceText.From(GeneratorConstants.EnumerationClass, Encoding.UTF8)); 15 | context.AddSource(nameof(GeneratorConstants.EnumerationClassAttribute), SourceText.From(GeneratorConstants.EnumerationClassAttribute, Encoding.UTF8)); 16 | 17 | if (context.SyntaxReceiver is not SyntaxReceiver receiver) 18 | return; 19 | 20 | CSharpParseOptions options = (context.Compilation as CSharpCompilation).SyntaxTrees[0].Options as CSharpParseOptions; 21 | Compilation compilation = context.Compilation.AddSyntaxTrees(CSharpSyntaxTree.ParseText(SourceText.From(GeneratorConstants.EnumerationClassAttribute, Encoding.UTF8), options)); 22 | INamedTypeSymbol attributeSymbol = compilation.GetTypeByMetadataName($"System.{nameof(GeneratorConstants.EnumerationClassAttribute)}"); 23 | 24 | var sources = new StringBuilder(); 25 | var assemblyName = ""; 26 | foreach (var @enum in receiver.Enums) 27 | { 28 | SemanticModel model = compilation.GetSemanticModel(@enum.SyntaxTree); 29 | var enumSymbol = model.GetDeclaredSymbol(@enum); 30 | 31 | var attr = enumSymbol.GetAttributes().FirstOrDefault(ad => ad.AttributeClass.Equals(attributeSymbol, SymbolEqualityComparer.Default)); 32 | 33 | if (attr == null) continue; 34 | var args = attr?.ConstructorArguments; 35 | 36 | var cls = (string)args.Value[0].Value ?? enumSymbol.Name + "Enumeration"; 37 | var nsp = (string)args.Value[1].Value ?? enumSymbol.ContainingNamespace.ToString(); 38 | assemblyName = enumSymbol.ContainingAssembly.Identity.Name; 39 | 40 | var codeBlock = new StringBuilder(); 41 | codeBlock.AppendLine($"namespace {nsp} {{"); 42 | 43 | codeBlock.AppendLine($"\tpublic partial class {cls} : Enumeration {{"); 44 | 45 | codeBlock.AppendLine($"\t\tpublic {cls}(int id, string name) : base(id, name) {{}}"); 46 | 47 | var members = enumSymbol.GetMembers().Where(x => x.Kind == SymbolKind.Field).Select(y => y.Name); 48 | 49 | var i = 0; 50 | foreach (var member in members) 51 | { 52 | codeBlock.AppendLine($"\t\tpublic static readonly {cls} {member} = new {cls}({++i}, nameof({member}));"); 53 | } 54 | 55 | codeBlock.AppendLine("\t}"); 56 | codeBlock.AppendLine("}"); 57 | 58 | sources.AppendLine(codeBlock.ToString()); 59 | 60 | } 61 | 62 | var code = new StringBuilder(); 63 | code.AppendLine("using System;"); 64 | code.AppendLine(sources.ToString()); 65 | var result = code.ToString(); 66 | context.AddSource($"{assemblyName}EnumerationGenerated", SourceText.From(result, Encoding.UTF8)); 67 | } 68 | 69 | public void Initialize(GeneratorInitializationContext context) 70 | { 71 | // System.Diagnostics.Debugger.Launch(); 72 | context.RegisterForSyntaxNotifications(() => new SyntaxReceiver()); 73 | } 74 | 75 | 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /EnumerationClassGenerator/GeneratorConstants.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace EnumerationClassGenerator 4 | { 5 | internal static class GeneratorConstants 6 | { 7 | internal const string EnumerationClassAttribute = @" 8 | namespace System 9 | { 10 | [AttributeUsage(AttributeTargets.Enum, Inherited = false, AllowMultiple = false)] 11 | public sealed class EnumerationClassAttribute : Attribute 12 | { 13 | public EnumerationClassAttribute(string @class = null, string @namespace = null) 14 | { 15 | } 16 | 17 | } 18 | }"; 19 | 20 | internal const string EnumerationClass = @" 21 | using System; 22 | using System.Collections.Generic; 23 | using System.Linq; 24 | using System.Reflection; 25 | 26 | public abstract class Enumeration : IComparable 27 | { 28 | public int Id { get; } 29 | public string Name { get;} 30 | 31 | protected Enumeration(int id, string name) 32 | { 33 | Id = id; 34 | Name = name; 35 | } 36 | 37 | public override string ToString() => Name; 38 | 39 | public static IEnumerable GetAll() where T : Enumeration 40 | { 41 | var fields = typeof(T).GetFields(BindingFlags.Public | 42 | BindingFlags.Static | 43 | BindingFlags.DeclaredOnly); 44 | 45 | return fields.Select(f => f.GetValue(null)).Cast(); 46 | } 47 | 48 | public override bool Equals(object obj) 49 | { 50 | var otherValue = obj as Enumeration; 51 | 52 | if (otherValue == null) 53 | return false; 54 | 55 | var typeMatches = GetType() == obj.GetType(); 56 | var valueMatches = Id.Equals(otherValue.Id); 57 | 58 | return typeMatches && valueMatches; 59 | } 60 | 61 | public override int GetHashCode() => Id.GetHashCode(); 62 | 63 | public static int AbsoluteDifference(Enumeration firstValue, Enumeration secondValue) 64 | { 65 | return Math.Abs(firstValue.Id - secondValue.Id); 66 | } 67 | 68 | public static T FromValue(int value) where T : Enumeration 69 | { 70 | return Parse(value, ""value"", item => item.Id == value); 71 | } 72 | 73 | public static T FromDisplayName(string displayName) where T : Enumeration 74 | { 75 | return Parse(displayName, ""display name"", item => item.Name == displayName); 76 | } 77 | 78 | private static T Parse(K value, string description, Func predicate) where T : Enumeration 79 | { 80 | var matchingItem = GetAll().FirstOrDefault(predicate); 81 | 82 | if (matchingItem == null) 83 | throw new InvalidOperationException($""'{value}' is not a valid {description} in {typeof(T)}""); 84 | 85 | return matchingItem; 86 | } 87 | 88 | private static bool TryParse(K value, string description, Func predicate, out T result) where T : Enumeration 89 | { 90 | var matchingItem = GetAll().FirstOrDefault(predicate); 91 | 92 | result = matchingItem; 93 | 94 | return matchingItem != null; 95 | } 96 | 97 | public int CompareTo(object other) => Id.CompareTo(((Enumeration)other).Id); 98 | 99 | }"; 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /EnumerationClassGenerator/SyntaxReceiver.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.CodeAnalysis; 2 | using Microsoft.CodeAnalysis.CSharp.Syntax; 3 | using System.Collections.Generic; 4 | 5 | namespace EnumerationClassGenerator 6 | { 7 | internal class SyntaxReceiver : ISyntaxReceiver 8 | { 9 | internal List Enums { get; } = new List(); 10 | 11 | public void OnVisitSyntaxNode(SyntaxNode syntaxNode) 12 | { 13 | if (syntaxNode is EnumDeclarationSyntax enumDeclaration 14 | && enumDeclaration.AttributeLists.Count > 0) 15 | { 16 | Enums.Add(enumDeclaration); 17 | } 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Hamed Fathi 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![code](https://user-images.githubusercontent.com/8418700/142345474-3ef91fec-380a-42e2-b95f-c6f04a8f58f5.png) 2 | 3 | ## Problem 4 | 5 | > Enumeration or Enum types are an integral part of C# language. They have been around since the inception of language. Unfortunately, the Enum types also have some limitations. Enum types are not object-oriented. When we have to use Enums for control flow statements, behavior around Enums gets scattered across the application. We cannot inherit or extend the Enum types. These issues can especially be a deal-breaker in Domain-Driven Design (DDD).
Read more [here](https://ankitvijay.net/2020/05/21/introduction-enumeration-class/) and [here](https://docs.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/enumeration-classes-over-enum-types). 6 | 7 | Regardless of the behaviors, there is a repetitive section where you have to write your class fields similar to what you have in a `enum` type. 8 | 9 | ```cs 10 | // Enum 11 | public enum CardType 12 | { 13 | Amex, 14 | Visa, 15 | MasterCard 16 | } 17 | 18 | // Converts to 19 | 20 | // Enumeration Class 21 | public class CardType : Enumeration 22 | { 23 | public static CardType Amex = new(1, nameof(Amex)); 24 | public static CardType Visa = new(2, nameof(Visa)); 25 | public static CardType MasterCard = new(3, nameof(MasterCard)); 26 | 27 | public CardType(int id, string name) 28 | : base(id, name) 29 | { 30 | } 31 | 32 | // Other behaviors 33 | } 34 | 35 | ``` 36 | 37 | ## Solution 38 | 39 | This generator helps you to focus on your business, no need to know about this pattern or details of `Enumeration` base class. 40 | 41 | Define your `enum` type` and put `EnumerationClass` attribute on top of it. 42 | 43 | ```cs 44 | namespace MyLibrary 45 | { 46 | [EnumerationClass] 47 | public enum CardType 48 | { 49 | Amex, 50 | Visa, 51 | MasterCard 52 | } 53 | } 54 | ``` 55 | 56 | Your enumeration class is ready and generated! before saying how to extend it, I should say how to find it! 57 | 58 | If you use parameter-less `EnumerationClass` the default options are: 59 | 60 | * Same `namespace` as you `enum` => `MyLibrary` for this sample. 61 | * The class name will be combination of `enum` type name + "Enumeration" => `CardTypeEnumeration` for this sample. 62 | 63 | But you can customize them: 64 | 65 | ```cs 66 | namespace MyLibrary 67 | { 68 | [EnumerationClass("MyClass", "MyNamespace")] 69 | public enum CardType 70 | { 71 | Amex, 72 | Visa, 73 | MasterCard 74 | } 75 | } 76 | ``` 77 | 78 | The generated class is `partial` to help you add your business rules, so you can find it as following based on above setting: 79 | 80 | ```cs 81 | // How to extend it? 82 | // Use same namespace name as you defined. 83 | // Use same class name as you defined. 84 | // Use 'partial' keyword for the class. 85 | // To access the base class functionality you should inherit from 'Enumeration'. 86 | 87 | namespace MyNamespace 88 | public partial class MyClass /*: Enumeration*/ 89 | { 90 | public void MyNewMethod() 91 | { 92 | // MasterCard 93 | } 94 | 95 | // ... 96 | } 97 | } 98 | ``` 99 | 100 | ## `Enumeration` Base Class 101 | 102 | As you can see there is a base class that provides some functionalities which includes the following: 103 | 104 | ```cs 105 | // Returns 'Name' property. 106 | override string ToString() 107 | 108 | // Returns all fields 109 | IEnumerable GetAll() 110 | 111 | // Returns difference of two enumerations in integer. 112 | int AbsoluteDifference(Enumeration firstValue, Enumeration secondValue) 113 | 114 | // Returns value from an integer number. 115 | T FromValue(int value) 116 | 117 | // Returns value from a string name. 118 | T FromDisplayName(string displayName) 119 | 120 | // Parse a value based on a condition. 121 | T Parse(K value, string description, Func predicate) 122 | 123 | // Parse a value based on a condition with an result. 124 | bool TryParse(K value, string description, Func predicate, out T result) 125 | 126 | // Returns status of comparison in number. 127 | int CompareTo(object other) 128 | ``` 129 | 130 |
131 | 132 | ### [Nuget](https://www.nuget.org/packages/EnumerationClassGenerator) 133 | 134 | [![Open Source Love](https://badges.frapsoft.com/os/mit/mit.svg?v=102)](https://opensource.org/licenses/MIT) 135 | ![Nuget](https://img.shields.io/nuget/v/EnumerationClassGenerator) 136 | ![Nuget](https://img.shields.io/nuget/dt/EnumerationClassGenerator) 137 | 138 | ``` 139 | Install-Package EnumerationClassGenerator 140 | 141 | dotnet add package EnumerationClassGenerator 142 | ``` 143 | 144 |
145 | 146 | ![1](https://user-images.githubusercontent.com/8418700/142345352-f5f306f3-a62d-4dc0-a9e4-d2f87dc827a5.png) 147 | 148 | ![2](https://user-images.githubusercontent.com/8418700/142345361-fb724ee1-5f47-4058-bb77-7af2d16f9fdd.png) 149 | 150 | ![3](https://user-images.githubusercontent.com/8418700/142345365-136dbf37-fd82-4a60-b03e-ae46104bb3b6.png) 151 | 152 |
153 | 154 |
Icons made by Freepik from www.flaticon.com
155 | 156 | 157 | --------------------------------------------------------------------------------