Read the value of an attribute of a method

C#.NetReflectionAttributesMethods

C# Problem Overview


I need to be able to read the value of my attribute from within my Method, how can I do that?

[MyAttribute("Hello World")]
public void MyMethod()
{
    // Need to read the MyAttribute attribute and get its value
}

C# Solutions


Solution 1 - C#

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");

Solution 2 - C#

[MyAttribute("Hello World")]
public int MyMethod()
{
var myAttribute = GetType().GetMethod("MyMethod").GetCustomAttributes(true).OfType<MyAttribute>().FirstOrDefault();
}

Solution 3 - C#

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), Array.Empty<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.

Solution 4 - C#

If you store the default attribute value into a property (Name in my example) on construction, then you can use a static Attribute helper method:

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);
    }
}

Usage:

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

My solution is based on that the default value is set upon the attribute construction, like this:

internal class MyAttribute : Attribute
{
    public string Name { get; set; }

    public MyAttribute(string name)
    {
        Name = name;
    }
}

Solution 5 - C#

In case you are implementing the setup like @Mikael Engver mentioned above, and allow multiple usage. Here is what you can do to get the list of all the attribute values.

[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class TestCase : Attribute
{
    public TestCase(string value)
    {
        Id = value;
    }

    public string Id { get; }        
}   

public static IEnumerable<string> AutomatedTests()
{
    var assembly = typeof(Reports).GetTypeInfo().Assembly;

    var methodInfos = assembly.GetTypes().SelectMany(m => m.GetMethods())
        .Where(x => x.GetCustomAttributes(typeof(TestCase), false).Length > 0);

    foreach (var methodInfo in methodInfos)
    {
        var ids = methodInfo.GetCustomAttributes<TestCase>().Select(x => x.Id);
        yield return $"{string.Join(", ", ids)} - {methodInfo.Name}"; // handle cases when one test is mapped to multiple test cases.
    }
}

Solution 6 - C#

I used this method :

public static TAttributeMember? GetMethodAttributeValue<TAttribute, TAttributeMember>(Expression<Func<object>> property, Func<TAttribute, TAttributeMember> valueSelector) where TAttribute : Attribute
{
    var methodInfo = ((MemberExpression)property.Body).Member as PropertyInfo;
    var attr = methodInfo?.GetCustomAttributes(typeof(TAttribute), true).FirstOrDefault() as TAttribute;
    return attr != null && valueSelector != null ? valueSelector(attr) : default(TAttributeMember);
}
    

Then can use like this:

var group = GetMethodAttributeValue<FieldAttribs, FieldGroups>(() => dd.Param2, a => a.Group);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCoppermillView Question on Stackoverflow
Solution 1 - C#SLaksView Answer on Stackoverflow
Solution 2 - C#NaggView Answer on Stackoverflow
Solution 3 - C#MafiiView Answer on Stackoverflow
Solution 4 - C#Mikael EngverView Answer on Stackoverflow
Solution 5 - C#Hoang MinhView Answer on Stackoverflow
Solution 6 - C#MohsenBView Answer on Stackoverflow