views:

60

answers:

3

I need to create a custom attribute that is applicable only for non static class member. How can I validate this constraint on project compilation or using code analysis tools?

+2  A: 

There's no such constraint.

Darin Dimitrov
It's true, we cannot use the AttrubuteUsageAttribute for this purpose.
klashar
A: 

You could always write some post-build event that uses reflection to verify this... Granted, it may not be the most elegant of solutions....

To set this up, you would go into project properties, then the 'Build Events' tab. You would then enter the command line for the reflection based tool you'd write to implement this verification

MPritch
I this there is some ability to add custom rule to code analysis tool to automate it.
klashar
A: 

It's probably not what you're looking for, but it's possible to make such an attribute with PostSharp, you will probably have something like this:

[Serializable]
public sealed class StaticAttribute : OnMethodBoundaryAspect
{
    public override bool CompileTimeValidate(System.Reflection.MethodBase method)
    {
        return method.IsStatic;
    }

The OnMethodBoundaryAspect basically wrapps your method inside a try/catch block, and the CompileTimeValidate method determines whether or not the attribute is invoked at runtime.

theburningmonk