Search code examples
c#attributescustom-attributesobject-initializerscollection-initializer

Can I use a collection initializer for an Attribute?


Can an attribute in C# be used with a collection initializer?

For example, I'd like to do something like the following:

[DictionaryAttribute(){{"Key", "Value"}, {"Key", "Value"}}]
public class Foo { ... }

I know attributes can have named parameters, and since that seems pretty similar to object initializers, I was wondering if collection initializers were available as well.


Solution

  • Update: I'm sorry I'm mistaken - pass array of custom type is impossible :(

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

    1. One of the following types: bool, byte, char, double, float, int, long, short, string.
    2. The type object.
    3. The type System.Type.
    4. An Enum type, provided it has public accessibility and the types in which it is nested (if any) also have public accessibility (Section 17.2).
    5. Single-dimensional arrays of the above types. source

    Source: stackoverflow.

    You CAN DECLARE passing an array of a custom type:

    class TestType
    {
      public int Id { get; set; }
      public string Value { get; set; }
    
      public TestType(int id, string value)
      {
        Id = id;
        Value = value;
      }
    }
    
    class TestAttribute : Attribute
    {
      public TestAttribute(params TestType[] array)
      {
        //
      }
    }
    

    but compilation errors occur on the attribute declaration:

    [Test(new[]{new TestType(1, "1"), new TestType(2, "2"), })]
    public void Test()
    {
    
    }