20

I'm using VS2008 and would like to create a compile time warning / error based on custom attributes on a property (if it is possible).

There are two cases which interest me currently:

[MyAttribute (typeof(MyClass)]

Where MyClass has to implement an interface. Currently I assert this in the constructor of the attribute, however this doesn't make it easy to track down, due to the nature of the stack trace:

public MyAttribute (Type MyClassType)
{
    System.Diagnostics.Debug.Assert(
        typeof(MyInterface).IsAssignableFrom(MyClassType),
        "Editor must implement interface: " + typeof(MyInterface).Name);
}

The second case which interests me is where I have a type defined in an attribute, if that type implements an interface, then a warning should be displayed if another attribute isn't present.

I.E. if (MyClass.Implements(SomeInterface) && !Exists(SomeAttibute)) { Generate Warning }

[MyAttribute(typeof(MyClass)] 
// Comment next line to generate warning
[Foo ("Bar")]

Thanks!

spaleet
  • 838
  • 2
  • 10
  • 23

1 Answers1

5

You can do that with PostSharp.

I've once done it, and explained how to do it here

Frederik Gheysels
  • 56,135
  • 11
  • 101
  • 154
  • Thanks a lot for that! I had looked at post sharp before (for another problem) and decided it against it, however now I think I will be re-evaluating ;) –  Sep 15 '09 at 01:11
  • I have just discovered a bit of an issue - it seems that GetCustomAttributes() no longer returns the attribute when it derives from PostSharp.Laos.OnMethodInvocationAspect rather than System.Attribute –  Sep 15 '09 at 02:56
  • You mean it returns System.Attribute ? Can't you cast it to your own attribute ? (GetCustomAttributes always returns an array of System.Attribute AFAIK, so you always have to cast i think ? – Frederik Gheysels Sep 15 '09 at 06:57
  • No, PostShap strips the Aspect attribute out of the metadata when it does its post compilation stage (ILDSAM confirms this). I did get around it by using CompoundAspect rather than OnMethodInvocationAspect as the base class. Then overriding ProvideAspects to re-insert itself into the metadata. -Phew-. Thanks Again :) –  Sep 15 '09 at 07:41
  • I have just discovered that using '[MulticastAttributeUsage(MulticastTargets.Property, PersistMetaData = true)]' removes the need for the CompoundAspect. –  Oct 09 '09 at 04:24
  • @FrederikGheysels - All of the code on your blog is a broken link. Could you post the code here? – ErnieL Mar 25 '13 at 16:20
  • This is a link to answer, not an answer itself. – Heretic Monkey Jan 08 '23 at 17:23