7

Is there any way of making a composite attribute in C# to provide equivalent metadata at compile time?

E.g, change:

[ClassInterface(ClassInterfaceType.AutoDual)]
[ProgId("MyProgId")]
[MyMefExport("MyProgId")]
public class MyClass
{
}

To:

[MyCompositeAttribute("MyProgId")]
public class MyClass
{
}
devdigital
  • 34,151
  • 9
  • 98
  • 120
  • 1
    What should be the effect of placing `MyCompositeAttribute` on a class? It looks like a single attribute, so it will make it to metadata as a single `MyCompositeAttribute`. – Sergey Kalinichenko Nov 21 '12 at 16:09
  • Don't think it's possible since your effectively asking for MyCompositeAttribute to inherit from more than one class. – Ian Quigley Nov 21 '12 at 16:11
  • Keep in mind that it's not so much about the code in the attributes themselves but in the different components that will be looking for each attribute. And you cannot use inheritance, because of the lack of multiple inheritance as @IanQuigley mentioned but also because attributes are typically sealed. – fsimonazzi Nov 21 '12 at 16:16
  • @dasblinkenlight The purpose of the first two attributes is for COM exposure, the third is for MEF export metadata (MyMefExport derives from ExportAttribute). The data (in this case 'MyProgId') is duplicated on two attributes, and the first attribute will always be constructed with 'AutoDual'. The desired behaviour is to maintain the functionality of each individual attribute. As the composite attribute couldn't use inheritance, I'm wondering if something like IL weaving could be achieved to replace the single attribute with the three corresponding attributes at compile time? – devdigital Nov 21 '12 at 16:36

2 Answers2

2

Attributes in and of themselves are meaningless. It is the code that enumerates the attributes attached to a class that may change its operation.

If you control the code that understands the attribute, you could create a composite attribute and act as though multiple separate attributes were applied.

That being said, I doubt you control ProgId nor the C# compiler that interprets it...

Mitch
  • 21,223
  • 6
  • 63
  • 86
1

Say you had the following code to read your custom attribute:

var attrs = typeof(MyClass).GetCustomAttributes(typeof(MyCompositeAttribute) ,false);

Any code that relied on say:

var attrs = typeof(MyClass).GetCustomAttributes(typeof(ProgId) ,false);

will fail to return that attribute.

Candide
  • 30,469
  • 8
  • 53
  • 60