views:

165

answers:

2

I'm writing some library code, and classes that use that code are required to have two attributes specified (one custom attribute and one from .NET).

It's a bit of a hassle to document this requirement and copy-and-paste both of those attributes onto every class that uses my library, so I thought it might be better to have my custom attribute just imply the presence of the other. That other attribute from the .NET framework is sealed, though, so I can't just inherit it...

So is there any way to do this? Can I maybe add the .NET attribute at runtime?

Thanks.

A: 

I do not believe there is a way to imply secondary attributes or to add attributes at runtime. However, you could use a custom code template to add the attributes to every class as you add them. And/or for classes that are already developed, I suspect you could write a macro that goes through each file and adds the attributes to the classes, however I have not done this in the past, so I'm not sure what it would entail, I know making a code template to add to attributes to a class declaration is relatively simple. But this only works for class you're adding from the point of template addition on. If you need to do cleanup to old classes as well, I would look into macros if you have a lot of files/classes this needs to be done for. Or do it manually if there are not too many.

Timothy Carter
+1  A: 

Whilst you can use inheritance in attributes it is recommended you don't.

Since this is only a performance rule you will not violate correctness but it can be a source of some confusion and you must spend a great deal of effort to ensure you do not violate the semantics of the base attribute. You may cause issues if you attempt to expand the possible locations for the attribute with the AttributeUsage flags. The rules for the attribute in question are quite complex.

A method can have either of the two attributes applied, but not both. Any operation that has neither applied uses the attribute applied to the containing class. If the containing class does not have either attribute applied, the DataContractSerializer is used.

Give this making it sealed sounds like a sensible plan on their part. This API is not designed with this sort of extension in mind.

There is no way (short of AOP style 'code injection') to add attributes to existing classes at runtime.

ShuggyCoUk
That makes sense. I'll just keep the runtime check to enforce the requirement.
Eric W