Can I initialize a C# attribute with an array or other variable number of arguments?

billmn picture billmn · Nov 6, 2008 · Viewed 80k times · Source

Is it possible to create an attribute that can be initialized with a variable number of arguments?

For example:

[MyCustomAttribute(new int[3,4,5])]  // this doesn't work
public MyClass ...

Answer

Mark Brackett picture Mark Brackett · Nov 6, 2008

Attributes will take an array. Though if you control the attribute, you can also use params instead (which is nicer to consumers, IMO):

class MyCustomAttribute : Attribute {
    public int[] Values { get; set; }

    public MyCustomAttribute(params int[] values) {
       this.Values = values;
    }
}

[MyCustomAttribute(3, 4, 5)]
class MyClass { }

Your syntax for array creation just happens to be off:

class MyCustomAttribute : Attribute {
    public int[] Values { get; set; }

    public MyCustomAttribute(int[] values) {
        this.Values = values;
    }
}

[MyCustomAttribute(new int[] { 3, 4, 5 })]
class MyClass { }