1

I define multiple attributes on a class:

[CustomAttribute("a", state = 0)]
[CustomAttribute("b", state = 0)]
...
[CustomAttribute("z", state = 0)]
public class MyClass { ... }

The values ("a", "b", on through to "z") are also used elsewhere in the program, so right now, I have a duplicate array of names.

public static readonly string[] listOfNames = new [] { "a", "b", ..., "z" };

I can recover the names from the attributes using reflection to build listOfNames, but is there a way to do the reverse and define the attributes from listOfNames? I suspect not, but then is there a clearer way to at least avoid repeating the CustomAttribute bit?

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
Matt Bierner
  • 58,117
  • 21
  • 175
  • 206

1 Answers1

1

You can use TypeDescriptor.AddAttributes to add class-level attributes to a type at run-time:

string[] listOfNames = new [] { "a", "b", "c" };
var attributes = listOfNames.Select(x=>new CustomAttribute(x)).ToArray();
TypeDescriptor.AddAttributes(typeof(MyClass), attributes);

Also as another option you can create a CustomTypeDescriptor for your type. In the custom type descriptor, you return custom PropertyDescriptor objects for the properties of your type and in the property descriptor, you return a custom set of attributes for the property. The key point in property descriptor is overriding Attributes property. Then create a TypeDescriptionProvider and register it for your type to provide the custom type description. This way you can use a single attribute instead of all those attributes.

To see an implementation take a look at this post: Combining Control Attributes.

Community
  • 1
  • 1
Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
  • Probably the first option satisfied you, while maybe it's enough for now, but keep the second solution in mind, it may help you in future, the linked post is really useful for cases which frameworks use standard .NET type description mechanisms. For example Windows Forms or ASP.NET MVC use the mechanism. – Reza Aghaei Aug 05 '16 at 18:40