Read the value of an attribute of a method
You need to call the GetCustomAttributes
function on a MethodBase
object.
The simplest way to get the MethodBase
object is to call MethodBase.GetCurrentMethod
. (Note that you should add [MethodImpl(MethodImplOptions.NoInlining)]
)
For example:
MethodBase method = MethodBase.GetCurrentMethod();
MyAttribute attr = (MyAttribute)method.GetCustomAttributes(typeof(MyAttribute), true)[0] ;
string value = attr.Value; //Assumes that MyAttribute has a property called Value
You can also get the MethodBase
manually, like this: (This will be faster)
MethodBase method = typeof(MyClass).GetMethod("MyMethod");
[MyAttribute("Hello World")]
public int MyMethod()
{
var myAttribute = GetType().GetMethod("MyMethod").GetCustomAttributes(true).OfType<MyAttribute>().FirstOrDefault();
}
The available answers are mostly outdated.
This is the current best practice:
class MyClass
{
[MyAttribute("Hello World")]
public void MyMethod()
{
var method = typeof(MyClass).GetRuntimeMethod(nameof(MyClass.MyMethod), new Type[]{});
var attribute = method.GetCustomAttribute<MyAttribute>();
}
}
This requires no casting and is pretty safe to use.
You can also use .GetCustomAttributes<T>
to get all attributes of one type.