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?
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.