How do you reflect on an attribute applied to a return value?
Asked Answered
S

1

10

Consider the following:

[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.ReturnValue)]
public class NotNullAttribute : Attribute
{
}

public class Class1
{
    [return: NotNull]
    public static string TestMethod([NotNull] string arg)
    {
        return arg + " + " + arg;
    }
}

How, using System.Reflection, would you see that the NotNullAttribute attribute had been applied to the return value of the method? If you can't, what is the purpose behind the [return: ] syntax?

Suprematism answered 15/4, 2010 at 19:16 Comment(0)
B
11

MethodInfo has a ReturnTypeCustomAttributes property, if you call GetCustomAttributes() on this you get the return value atrtibutes.

MethodInfo mi = typeof(Class1).GetMethod("TestMethod");
object[] attrs = mi.ReturnTypeCustomAttributes.GetCustomAttributes(true);
Bags answered 15/4, 2010 at 19:32 Comment(3)
Gah. Your answer made me realize that PostSharp is using MethodBase, and that's why that wasn't available. Thanks.Suprematism
BTW, if you're loading assemblies into a READ-ONLY context (which I was despite my simplified test case above not doing so), this solution actually won't work. Instead, you have to use: CustomAttributeData.GetCustomAttribute(methodInfo.ReturnParameter)Kosciusko
There is also mi.ReturnParameter.GetCustomAttributes etc. @Amy, The reason why they are not available on MethodBase seems to be that constructors do not allow return types, while "non-constructor methods" do (they are C# methods, C# accessors for properties/indexers/events, C# operators). Methods that return void can also have custom attributes on their return values!Derrickderriey

© 2022 - 2024 — McMap. All rights reserved.