creating enumeration using .NET's CodeDom
Asked Answered
H

1

12

I want to create an Enumeration using CodeDom API. I have searched enough on the internet and I get results which are hardly of any use.

What I want to generate is

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 set it's IsEnum property as true, created a name, and set it's Attributes.

Now the biggest problem is how to populate 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);

Though using this solution I can generate the Description attributes, the end of line would be ; and not ,

Hufuf answered 17/4, 2010 at 7:10 Comment(0)
M
20

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 member name. In your real code, of course, these can be different.)

A 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 permitted by the C# language, precisely in order to support generated-code scenarios like this, and will compile fine even if it looks a bit odd to the human reader.

Monachism answered 17/4, 2010 at 7:33 Comment(4)
Nicely put - it isn't particularly obvious that enums are in fact a type of CodeMemberField. Useful information in other contexts!Flexure
Agreed, very nicely put. The fact that the values for an enum are fields probably stems from the way they are actually stored in the .Net binary, as a set of static fields with a constant value.Anacoluthon
How would you assign an enum value via codedom? As in Bugzilla = 1, Redmine = 2, etc.?Soutane
Use InitExpression (e.g. f.InitExpression = new CodePrimitiveExpression(value));Soutane

© 2022 - 2024 — McMap. All rights reserved.