Creating an Enumeration Using .NET CodeDom

I want to create Enumeration using the CodeDom API . I have searched enough on the Internet and I am getting results that are unlikely to be useful.

I want to create

 public enum bug_tracker_type { [Description("Bugzilla")] Bugzilla, [Description("Debbugs")] Debbugs, [Description("PHP Project Bugtracker")] PHP_Project_Bugtracker, [Description("Google Code")] Google_Code } 

I used CodeTypeDeclaration and assigned the IsEnum property to true, created a name and set its attributes.

Now the biggest problem is how to fill the body?

I tried

 CodeTypeMember mem = new CodeTypeMember(); mem.Name = WadlSharpUtils.CreateIdentifier(discreteValue.value); mem.CustomAttributes.Add(new CodeAttributeDeclaration(discreteValue.value)); // enumCandidate is an instance of CodeTypeDeclaration enumCandidate.Members.Add(mem); 

Although using this solution I can generate description attributes, the end of the line will be ; and not

+7
c # codedom
source share
1 answer

Enum members are fields, so use CodeMemberField:

 CodeTypeDeclaration type = new CodeTypeDeclaration("BugTracker"); type.IsEnum = true; foreach (var valueName in new string[] { "Bugzilla", "Redmine" }) { // Creates the enum member CodeMemberField f = new CodeMemberField("BugTracker", valueName); // Adds the description attribute f.CustomAttributes.Add(new CodeAttributeDeclaration("Description", new CodeAttributeArgument(new CodePrimitiveExpression(valueName)))); type.Members.Add(f); } 

(In this simplified code, the description will always be the same as the name of the participant. In your real code, of course, they can be different.)

The little quirk you may notice is that CodeDom adds a comma after the last enum value:

 public enum BugTracker { [Description("Bugzilla")] Bugzilla, [Description("Redmine")] Redmine, // trailing comma } 

This is allowed in C # to support scripts of generated code like this, and will compile fine even if it looks a little strange to the reader.

+11
source share

All Articles