Can anybody explain why I can’t use a const Int32 in an C# attribute?
Example:
private const Int32 testValue = 123;
[Description("Test: " + testValue)]
public string Test { get; set; }
Makes the compiler say:
“An attribute argument must be a constant expression, …”
Why?
As the error states, an attribute argument must be a constant expression.
Concatenating a string and an integer is not a constant expression.
Thus, if you pass
"Test: " + 123directly, it will give the same error.On the other hand, if you change
testValueto a string, it will compile.Explanation
The rules for constant expressions state that a constant expression can contain arithmetic operators, provided that both operands are themselves constant expressions.
Therefore,
"A" + "B"is still constant.However,
"A" + 1uses thestring operator +(string x, object y);, in which the integer operand is boxed to an object.The constant-expression rules explicitly state that