Arrays of Types in attributes

I want to pass array of Types to attribute, I tried do it this way

class CustomAttribute: Attribute 
{
   Type[] included;
   Type[] excluded;
}

[CustomAttribute{included = new Type[] {typeof(ComponentA)}, 
                 excluded = new Type[] {typeof(ComponentB)} }]//dont work  
class Processor 
{
   // something here
}

but VS show cant pass Types in attribute.

Do somebody know how to resolve this issue or eventual workaround ?

Jon Skeet
people
quotationmark

It looks like this has nothing to do with arrays, but everything to do with your general syntax. You're using { } for attribute arguments instead of ( ), and your attribute doesn't have public properties, which are required for named arguments in attributes. Additionally, your attribute class doesn't use [AttributeUsage(...)].

Here's a complete example which does compile:

using System;

[AttributeUsage(AttributeTargets.All)]
class CustomAttribute : Attribute 
{
    public Type[] Included { get; set; }
    public Type[] Excluded { get; set; }
}

[CustomAttribute(Included = new Type[] { typeof(string) },
                 Excluded = new Type[] { typeof(int), typeof(bool) })]
class Processor 
{
}

To make things briefer:

  • You can provide a constructor with parameters
  • You can use new[] instead of new Type[]

So:

using System;

[AttributeUsage(AttributeTargets.All)]
class CustomAttribute : Attribute 
{
    public Type[] Included { get; set; }
    public Type[] Excluded { get; set; }

    // Keep a parameterless constructor to allow for
    // named attribute arguments
    public CustomAttribute()
    {
    }

    public CustomAttribute(Type[] included, Type[] excluded)
    {
        Included = included;
        Excluded = excluded;
    }
}

[CustomAttribute(new[] { typeof(string) }, new[] { typeof(int), typeof(bool) })]
class Processor 
{
    // Provide the named version still works
    [CustomAttribute(Included = new[] { typeof(string) },
                     Excluded = new[] { typeof(int), typeof(bool) })]
    public void Method()
    {
    }
}

people

See more on this question at Stackoverflow