1
public class A
{
    [Description("This method does something")]
    public void TestMethod()
     {
       //Do Something
     }
}

My question is how do I get the string value of the Description Attribute using reflection.

Ujjal Das
  • 77
  • 1
  • 7

2 Answers2

1
var description = ((DescriptionAttribute)typeof (A).GetMethod("TestMethod")
    .GetCustomAttribute(typeof (DescriptionAttribute))).Description;
Scott Hannen
  • 27,588
  • 3
  • 45
  • 62
  • public void GetDescription() { MethodInfo[] methods = typeof(A).GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); Dictionary methodInformations = new Dictionary(); foreach(var method in methods) { object attrs = method.GetCustomAttribute(typeof(DescriptionAttribute)); DescriptionAttribute decr = attrs as DescriptionAttribute; methodInformations.Add(method.Name, decr.Description); } } – Ujjal Das Aug 03 '16 at 14:13
  • The above method also helped me in filtering the base class method as the class A was a derived class – Ujjal Das Aug 03 '16 at 14:15
0

You can try like this:

MethodBase m = typeof(A).GetMethod("TestMethod");;
Description d = (Description)m.GetCustomAttributes(typeof(Description), true)[0] ;
string str= d.Value; 
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331