4

This may be more of a design question then a "Can I do this?" question. I'm creating an attribute which its target is defined as Method. Is there any possible way to impose restrictions on the domain of methods,i.e that the target method must be declared abstract, virtual, static, etc?

The ultimate goal is to scan for these methods and implement them in a subclass--however I'd like them to be abstract. Is there a better way to accomplish this psuedo-restriction on targets of my attribute?

OnResolve
  • 4,016
  • 3
  • 28
  • 50

2 Answers2

3

You should be able to filter out non-virtual methods which are decorated with your attribute using MethodInfo.IsVirtual and MethodInfo.IsAbstract to get determine if it is abstract.

foreach(var assem in AppDomain.CurrentDomain.GetAssemblies())
    foreach (var type in assem.GetTypes())
        foreach (var mthdInfo in type.GetMethods())
        {
            if (mthdInfo.GetCustomAttributes(typeof(MyCustomAttribute), false) && mthdInfo.IsVirtual && !mthdInfo.IsFinal)
                // This is a method you can use
        }

There are ways to detect the other constraints you listed as well and the approach should be similar.

EDIT: Fixed to answer the question for methods.

M.Babcock
  • 18,753
  • 6
  • 54
  • 84
  • Thanks for the comment; On the implementation side (i.e when I handle them) I will be doing the checking you listed. However, and perhaps I worded my question poorly, I'd like to avoid confusion on my end-user, the one decorating their method with my attribute. Say, they have a non-virtual, non-abstract method that they place my attribute on--I can't perform my operation on the method, but I also can't throw an exception as to break their program either. My hope was that the CLR could have caught this by imposing a restriction that doesn't let offenders get past compilation. – OnResolve Mar 06 '12 at 17:35
  • There isn't anything in the runtime or the compiler that will allow you to hook at the level you're looking for. I believe this is something Roslyn will allow you to do in the future though. As an alternative you could write a thin console application that your users would run in their post build actions which would reflect on the built assembly, do these checks, and dump out any methods that don't conform. – M.Babcock Mar 06 '12 at 17:38
2

Nope, sorry. You can play around with the Inherited argument in AttributeUsage though, it may help you somewhat.

Edit: I know this post doesn't address your question directly, but you may be able to apply some of the principals it discusses:

Restrict custom attribute so that it can be applied only to Specifc types in C#?

Community
  • 1
  • 1
eouw0o83hf
  • 9,438
  • 5
  • 53
  • 75