Generating a custom compile time warning C#
Asked Answered
O

1

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!

Okoka answered 14/9, 2009 at 7:32 Comment(1)
F
5

You can do that with PostSharp.

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

Flooring answered 14/9, 2009 at 7:39 Comment(7)
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 ;)Okoka
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.AttributeOkoka
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 ?Flooring
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 :)Okoka
I have just discovered that using '[MulticastAttributeUsage(MulticastTargets.Property, PersistMetaData = true)]' removes the need for the CompoundAspect.Okoka
@FrederikGheysels - All of the code on your blog is a broken link. Could you post the code here?Sessile
This is a link to answer, not an answer itself.Quiteris

© 2022 - 2024 — McMap. All rights reserved.