AFAIK, named parameters allow only integral types. Unfortunately, I have no references to this; I only found out in my experiments.
When trying to use object initializers, I received this error from the compiler:
The attribute argument must be a constant expression, a typeof expression, or an array creation expression type attribute attribute
Although this documentation is several years old, it does have the background information I was looking for:
Attribute parameters are limited by constant values โโof the following types:
- Simple types (bool, byte, char, short, int, long, float and double)
- line
- System.Type
- enums
- object (The argument parameter argument of an object of type must be a constant value of one of the above types.) One-dimensional arrays of any of the specified types.
So this works:
//Test attribute class [AttributeUsage(AttributeTargets.All)] internal class TestAttribute : Attribute { public int[] Something { get; set; } } //Using an array initialiser - an array of integers [TestAttribute(Something = new int[]{1, 2, 3, 4, 5})] public abstract class Something
If this is not the case:
EDIT: just to clarify, attributes form part of the metadata for the constructs to which they apply (inside the generated IL), so members of the attribute class must be defined at compile time; therefore, the restriction of attribute parameters to constant values.
James shuttler
source share