Read method attribute value

I need to be able to read the value of my attribute from my method, how can I do this?

[MyAttribute("Hello World")] public void MyMethod() { // Need to read the MyAttribute attribute and get its value } 
+41
reflection methods c # attributes
Mar 22 '10 at 14:52
source share
4 answers

You need to call the GetCustomAttributes function of the GetCustomAttributes object.
The easiest way to get a MethodBase object is to call MethodBase.GetCurrentMethod . (Note that you must 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 a MethodBase manually, for example: (This will be faster)

 MethodBase method = typeof(MyClass).GetMethod("MyMethod"); 
+50
Mar 22
source share
 [MyAttribute("Hello World")] public int MyMethod() { var myAttribute = GetType().GetMethod("MyMethod").GetCustomAttributes(true).OfType<MyAttribute>().FirstOrDefault(); } 
+23
Mar 22
source share

Available answers are mostly out of date.

This is the 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>(); } } 

It does not require casting and is fairly safe to use.

You can also use .GetCustomAttributes<T> to get all attributes of the same type.

+11
Sep 30 '16 at 14:07
source share

If you save the default attribute value as a property ( Name in my example) when building, you can use the static attribute attribute:

 using System; using System.Linq; public class Helper { public static TValue GetMethodAttributeValue<TAttribute, TValue>(Action action, Func<TAttribute, TValue> valueSelector) where TAttribute : Attribute { var methodInfo = action.Method; var attr = methodInfo.GetCustomAttributes(typeof(TAttribute), true).FirstOrDefault() as TAttribute; return attr != null ? valueSelector(attr) : default(TValue); } } 

Using:

 var name = Helper.GetMethodAttributeValue<MyAttribute, string>(MyMethod, x => x.Name); 

My solution is based on the fact that the default value is set to build the attribute, for example:

 internal class MyAttribute : Attribute { public string Name { get; set; } public MyAttribute(string name) { Name = name; } } 
0
Feb 12 '17 at 18:18
source share



All Articles