Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a custom attribute imply other attributes without inheritance?

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.

like image 558
Eric W Avatar asked Nov 05 '22 20:11

Eric W


2 Answers

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.

like image 169
ShuggyCoUk Avatar answered Nov 12 '22 22:11

ShuggyCoUk


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.

like image 32
Timothy Carter Avatar answered Nov 12 '22 22:11

Timothy Carter