Can I restrict a user attribute to void methods only?

I have a custom attribute that I would like to limit to methods with a return type of void.

I know that I can restrict methods using [AttributeUsage(AttributeTargets.Method)] , but there seems to be no way to limit the return type or any other aspect of the method signature.

The [System.Diagnostics.Conditional] attribute has exactly the limitation that I want. Adding it to a non-empty method results in a compiler error:

The conditional attribute is not valid in '(SomeMethod)' because its return type is not void

and IntelliSense says:

The 'System.Diagnostics.ConditionalAttribute' attribute is valid only for attribute classes or methods with a return type of 'void'.

If I am F12 in ConditionalAttribute , I see that it is decorated with the following attributes:

[Serializable]
[AttributeUsage (AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
[ComVisible (true)]

Nothing is said about the return type.

How do I do this for the Conditional attribute and can I do the same for my custom attribute?

+7
c # attributes custom-attributes postsharp
source share
2 answers

Turns out there was a solution in my particular case since I used PostSharp.

My custom attribute inherits from PostSharp.Aspects.MethodInterceptionAspect (which inherits from Attribute ), which has an CompileTimeValidate(MethodBase method) .

This allows you to emit compiler errors during build:

 public override bool CompileTimeValidate(MethodBase method) { Debug.Assert(method is MethodInfo); var methodInfo = (MethodInfo)method; if (methodInfo.ReturnType != typeof(void)) { Message.Write( method, SeverityType.Error, "CX0001", "The Foo attribute is not valid on '{0}' because its return type is not void", method.Name); return false; } return true; } 
+4
source share

Most attributes are simply metadata that are class bound and that can be checked at runtime. However, some attributes are used by the compiler. System.ObsoleteAttribute for example, can be used so that the compiler emits errors or warnings if a method, class, etc. is used. System.Diagnostics.ConditionalAttribute is another example of an attribute used by the compiler. Thus, the compiler itself can impose rules for its use, which cannot be applied to other attributes (for example, only for void methods).

Unfortunately, at the moment it is not possible to affect the compiler, although custom attributes. When Rosalynn writes to C #, the path is then opened so that the compiler code runs inside the attribute as part of the compilation phase. Your example attribute limit for void methods would be one such way of using this function if it were to be implemented.

+3
source share

All Articles