1

How do I create a "Custom Attribute" so that it can only be applied to "virtual" methods?

Here should be fine:

[OnlyOnVirtual]
public virtual void VirtualMethod()
{
    //do something
}

And here, I would like to raise a compilation or execution error:

[OnlyOnVirtual]
public void NonVirtualMethod()
{
    //do something
}

Is it possible to create a "Custom Attribute" with that kind of restriction?

Hailton
  • 1,192
  • 9
  • 14
  • Why do you want to do this? It seems like a design smell. – Paul Phillips Jul 27 '12 at 23:30
  • @PaulPhillips. This attribute will be used to AOP through Spring.Net. If the method is not virtual, nothing happens and most developers on my team can not identify easily why the Aspect does not work. The goal is to easily identify this "problem" at development time. – Hailton Jul 27 '12 at 23:43
  • 1
    You can probably get it to throw an exception at runtime, although I don't know enough about the framework to suggest how. The failing silently part sounds like the problem. Also, you don't have to use the '@' replies when it's just two of us in the comments. – Paul Phillips Jul 27 '12 at 23:45

4 Answers4

4

No. That kind of restriction is not supported.

Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
2

You can't cause a compilation error for this usage, but you can throw a runtime exception in whatever code you have that's consuming the attributed methods. This is a very typical approach for cases where the usage requirements are more than the compiler can enforce. Note that you can't cause a general 'execution error' (outside your code that performs the reflection), as attributes are metadata and are only 'used' at runtime when code is reflecting over them.

Dan Bryant
  • 27,329
  • 4
  • 56
  • 102
0

See AttributeTargets enum about the types you can apply your attribute.

Example:

 [AttributeUsage(AttributeTargets.Class)]
    public class MyAttribute : Attribute
    {

    }
Embedd_0913
  • 16,125
  • 37
  • 97
  • 135
0

As mentions in the post below, you can not force compiler to check this as compile step, but you can check it in runtime on application start - just check that all methods where you applied attribute are virtual.

C# Method Attribute force requirements such as abstract or static?

Community
  • 1
  • 1
Dmytro Kutetskyi
  • 701
  • 6
  • 11