I have a custom attribute which I would like to restrict to methods with return type void.
I know I can restrict to methods using [AttributeUsage(AttributeTargets.Method)]
but there doesn't seem to be a way to restrict the return type or any other aspect of the methods signature.
The [System.Diagnostics.Conditional]
attribute has exactly the kind of limitation I want. Adding it to a non-void method results in the compiler error:
The Conditional attribute is not valid on '(SomeMethod)' because its return type is not void
and IntelliSense says:
Attribute 'System.Diagnostics.ConditionalAttribute' is only valid on attribute classes or methods with 'void' return type.
If I F12 to the ConditionalAttribute
I see that it is decorated with the following attributes:
[Serializable]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
[ComVisible(true)]
None of which says anything about the return type.
How is it done for the Conditional
attribute and can I do the same for my custom attribute?
System.Diagnostics.ConditionalAttribute
source is unremarkable in that effect (dotnetframework.org/default.aspx/4@0/4@0/DEVDIV_TFS/Dev10/…). It must be some compiler magic. Rosalyn and C#6 may change that though. – Nonpartisan