3

I'm using CodeDom to generate code to be compiled later, and I've noticed that certain constructs create extra sets of parentheses. While I know they don't affect anything, they do look strange.

A sample of code that does it is this:

new CodeConditionStatement(
  new CodeBinaryOperatorExpression(
    new CodePropertyReferenceExpression(new CodePropertySetValueReferenceExpression(), 
      "Length"),
    CodeBinaryOperatorType.GreaterThan,
    new CodePrimitiveExpression(strLength)
  ),
  new CodeThrowExceptionStatement(
    new CodeObjectCreateExpression(typeof(ArgumentException), 
    new CodePrimitiveExpression("The string is too long"), 
    new CodePrimitiveExpression("value"))
  )
)

This generates the following snippet:

if ((value.Length > 50)) {
    throw new System.ArgumentException("The string is too long", "value");
}

Again, I know that the extra parentheses don't affect anything, but if I'm doing something wrong to do this, I'd like to know :)

Akram Shahda
  • 14,655
  • 4
  • 45
  • 65
Mike Caron
  • 14,351
  • 4
  • 49
  • 77

2 Answers2

1

Looks good to me. I've been getting the same resulting code for ages.

If you're only interested in code gen for C#, you could spell out the condition with CodeSnippetExpression, avoiding the extra parentheses. Your way is more general.

Under the hood, IL does not do parentheses resolution (it's the compiler's job), so if parentheses might be needed, they will be included explicitly.

GregC
  • 7,737
  • 2
  • 53
  • 67
1

My guess would be that the authors of the CodeDom didn't feel the advantage of a bit cleaner code would weight out against using the precious CPU time required to detect the need for the parentheses. In some other cases they might have been really needed.

Jan-Peter Vos
  • 3,157
  • 1
  • 18
  • 21
  • That seems as reasonable as anything. After all, generated code is not meant to be looked at :) – Mike Caron May 30 '11 at 20:57
  • @Mike Caron: except for when you are trying to debug that generated code, or the code generator itself. Been there, done that. (Not that this is an issue with the extra braces though :-) – Christian.K May 31 '11 at 04:25