Ev.
Ev.

Reputation: 7589

How do access the attributes of a method's Parameters

How do you determine if a parameter has a custom attribute attached to it?

I thought this test case would pass:

    [TestCase("")]
    public void TestParameterAttribute([NotRequired]string theString)
    {
        var result = false;

        foreach (var attribute in theString.GetType().GetCustomAttributes(true))
        {
            if (attribute.GetType() == (typeof(NotRequiredAttribute)))
            {
                result = true;
            }
        }

        Assert.That(result, Is.True);
    }

Upvotes: 0

Views: 185

Answers (3)

Selman Genç
Selman Genç

Reputation: 101681

Also you can use Generic version of GetCustomAttribute method:

parameter.GetCustomAttribute<NotRequiredAttribute>() != null

Upvotes: 1

Simon Whitehead
Simon Whitehead

Reputation: 65079

theString.GetType() gets a reference to the Type representing a string. Calling GetCustomAttributes on it will look in the string class for those attributes.

What you want to do.. is get the attributes for the parameters in the current method. Maybe something like this:

var result = false;

foreach (var parameter in MethodInfo.GetCurrentMethod().GetParameters())
{
    if (parameter.GetCustomAttributes().Any(x => x.GetType() == typeof (NotRequiredAttribute)))
        result = true;
}

Upvotes: 1

Wagner DosAnjos
Wagner DosAnjos

Reputation: 6374

It requires a little bit more work.

[TestCase("")]
public void TestParameterAttribute([NotRequired]string theString)
{
    var method = MethodInfo.GetCurrentMethod();
    var parameter = method.GetParameters()[0];
    var result = false;

    foreach (var attribute in parameter.GetCustomAttributes(true))
    {
        if (attribute.GetType() == (typeof(NotRequiredAttribute)))
        {
            result = true;
        }
    }

    Assert.That(result, Is.True);
}

Upvotes: 1

Related Questions