Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An attribute argument must be a constant expression

Tags:

.net

Is there any workaround for the following issue?

An attribute argument must be a constant expression

I want to use decimals in an attribute’s parameter.

like image 638
jio Avatar asked May 04 '10 08:05

jio


1 Answers

Unfortunately you can't use decimals in attribute values, as the CLR itself doesn't really know about System.Decimal type - it's not a primitive type like int, double etc. The C# compiler basically fakes it for const fields of type decimal, but it can't achieve the same effect with attributes.

From the C# 3 spec, section 17.1.3:

The types of positional and named parameters for an attribute class are limited to the attribute parameter types, which are:

  • One of the following types: bool, byte, char, double, float, int, long, sbyte, short, string, uint, ulong, ushort.
  • The type object.
  • The type System.Type.
  • An enum type, provided it has public accessibility and the types in which it is nested (if any) also have public accessibility (§17.2).
  • Single-dimensional arrays of the above types.

Then later in section 17.2:

An expression E is an attribute-argument-expression if all of the following statements are > true:

  • The type of E is an attribute parameter type (§17.1.3).
  • At compile-time, the value of E can be resolved to one of the following:
    • A constant value.
    • A System.Type object.
    • A one-dimensional array of attribute-argument-expressions.
like image 73
Jon Skeet Avatar answered Sep 23 '22 07:09

Jon Skeet