Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use int constant in attribute

Tags:

c#

constants

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?

like image 728
Sascha Avatar asked Jan 09 '13 19:01

Sascha


1 Answers

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.


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" + 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.

like image 81
SLaks Avatar answered Sep 28 '22 03:09

SLaks