Reputation: 8780
How do I get at the attribute of the parameter in the following code?
public void SomeMethod([SomeAttribute] string s)
{
var someAttribute = ?
}
And I realize the attribute isn't generally for use inside the method it's on... just keeping the example simple though.
Upvotes: 0
Views: 36
Reputation: 1062695
First you need a MethodInfo
:
var method = typeof(SomeType).GetMethod("SomeMethod");
Then you can check for existence:
bool hasAttrib = Attribute.IsDefined(
method.GetParameters()[0], typeof(SomeAttribute));
or get an instance (more expensive):
var attrib = (SomeAttribute) Attribute.GetCustomAttribute(
method.GetParameters()[0], typeof(SomeAttribute));
Upvotes: 2
Reputation: 8780
I just figured it out:
var someAttribute = typeof(SomeClass).GetMethod("SomeMethod").GetParameters().First().GetCustomAttributes(false);
I just had a brain fart and was using the Attributes property instead of the GetCustomAttributes method.
Upvotes: 2