RCPT RCPT -4 years ago 44
C# Question

Access to the value of a Custom Attribute

Ive got this Custom Attribute:

[AttributeUsage(AttributeTargets.Method, AllowMultiple=false, Inherited = true)]
class MethodTestingAttibute : Attribute
{
public string Value{ get; private set; }
public MethodTestingAttibute (string value)
{
this.Value= value;

}
}


To be used like this:

[MethodTestingAttibute("2")]
public int m1() {return 3; }


And my dificulty is to take the Value of "2" of the MethodTestingAttibute

object result = method.Invoke(obj, new Type[] {}); // here i get the return


Now i want to compare this result to the Value of the Method TestingAttibute. How i can do that? Im trying to go up to this road but without success: method.GetCustomAttributes(typeof(MethodTestAttibute), true)[0]...

What is the properly to get access to the field of the Custoum Attribute?

Answer Source
var attribute =
   (MethodTestingAttibute)
   typeof (Vehicles)
      .GetMethod("m1")
      .GetCustomAttributes(typeof (MethodTestingAttibute), false).First();
Console.WriteLine(attribute.Value);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download