views:

90

answers:

2

Hi,

I would like to define a constrait on my custom (PostSharp) attribute. My goal is to get error or warning while compile time, if class X dont implements Y interface but it has my attribute.

So this should work:

[MyAttributeOnlyForY]
public class X : Y { ... }

but this should break the compile process:

[MyAttributeOnlyForY]
public class X { ... }

How is it possible?

The reason

This attribute works like an aspect (this is PostSharp attribute), and I want to be sure that the weaved class provides all needed information for this attribute.

I want to avoid null result on

(eventArgs.Instance as ILoggerServiceOwner)

and I think complie time checking is a good practice.

Solution

I've found a perfect start here: Validating attribute usage with PostSharp Aspects

+1  A: 

I think this is not possible. A better solution might be to use the Obsolete attribute on your custom attribute constructor to warn that the target class should implement the interface Y.

Islam Ibrahim
It's good for Plan B:)
boj
+1  A: 

You could use the PostSharp method CompileTimeValidate and use reflection to check if type has a derived type. However, it may be computationally expensive do look for all types in the assembly.

Gael Fraiteur
and some ideas from here: http://www.postsharp.org/forum/postsharp-laos/onmethodboundaryaspect-compiletimevalidate-param-issues-t333.html
boj