views:

60

answers:

1

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?

+1  A: 

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);
Chris Taylor
Gah. Your answer made me realize that PostSharp is using MethodBase, and that's why that wasn't available. Thanks.
yodaj007