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: " + 123
directly, it will give the same error.
On the other hand, if you change testValue
to a string, it will compile.
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" + 1
uses the string operator +(string x, object y);
, in which the integer operand is boxed to an object.
The constant-expression rules explicitly state that
Other conversions including boxing, unboxing and implicit reference conversions of non-null values are not permitted in constant expressions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With