Wednesday, 3 June 2009

Code Generation - Attributes with Enum Values

Adding attributes to a class seemed straight forward when writting a class to do some code generation, adding Enum values to the attribute didn't.

Here is the code for adding an attribute with a string value:

    1 type.CustomAttributes.Add(
    2     new CodeAttributeDeclaration(new CodeTypeReference(typeof (RangeAttribute)),
    3                                  new CodeAttributeArgument("Min",
    4                                                            new CodePrimitiveExpression("1"))));

Knowing how to add the Enum wasn't at first obvious until (after some googling and experimentation) I figured out that an enum value is really a field...obvious...

...ok, not so, but here is the result:

    1 var enumTypeExpression = new CodeTypeReferenceExpression(typeof(Format));
    2 var enumValueExpression = new CodeFieldReferenceExpression(enumTypeExpression, Format.Bool.ToString());
    3 
    4 type.CustomAttributes.Add(
    5     new CodeAttributeDeclaration(
    6         new CodeTypeReference(typeof (FormatAttribute)),
    7         new CodeAttributeArgument("Format", enumValueExpression)));

Submit this story to DotNetKicks Shout it

No comments:

Post a Comment