Is it possible to encode a user attribute that breaks the assembly (e.g. System.ObsoleteAttribute)?

I would like to create a custom attribute that runs during the build process, and can break the assembly according to some logic very similar to System.ObsoleteAttribute .

For example, consider the following C # code (note that this is a simplified example):

 public class MyClass { [Check] public int MyProp { get; private set; } } 

This Check attribute should verify that the property that it adorns has a public setter. Since the MyProp property MyProp not have a public setter (it has its own setter), the Check attribute should break the assembly.

Is it possible?

+4
source share
1 answer

No - at least not now, with standard building tools. It is possible that when the compiler as a service project is submitted, this may reveal this functionality. But the C # compiler does change its behavior to a few well-known attributes.

Two options you can consider:

  • Postprocessing with something like PostSharp
  • Unit test to find all attributes and test them in this way

Personally, I will probably go with the latter ... although there really is no obvious benefit - if you remember to declaratively add the [Check] attribute, would you not want to add a public setter? Or, to put it another way: if you forgot to enable the public setter, can't you forget to enable this attribute?

+3
source

All Articles