Access to the value of a Custom Attribute

To get the value of an attribute property, just cast the object returned by GetCustomAttributes():

{
    string val;
    object[] atts = method.GetCustomAttributes(typeof(MethodTestAttibute), true);
    if (atts.Length > 0)
       val = (atts[0] as MethodTestingAttibute).Value;
}

var attribute =
   (MethodTestingAttibute)
   typeof (Vehicles)
      .GetMethod("m1")
      .GetCustomAttributes(typeof (MethodTestingAttibute), false).First();
Console.WriteLine(attribute.Value);

With my custom attribute:

[AttributeUsage(AttributeTargets.Method)]
public class AttributeCustom : Attribute
{
    public string MyPropertyAttribute { get; private set; }

    public AttributeCustom(string myproperty)
    {
        this.MyPropertyAttribute = myproperty;
    }
}

I create a method for to get attribute with his values:

public static AttributeCustom GetAttributeCustom<T>(string method) where T : class
{
    try
    {
        return ((AttributeCustom)typeof(T).GetMethod(method).GetCustomAttributes(typeof(AttributeCustom), false).FirstOrDefault());
    }
    catch(SystemException)
    {
        return null;
    }
}

With a example class (must be not static because T is generic)

public class MyClass
{
    [AttributeCustom("value test attribute")])
    public void MyMethod() 
    {
        //...
    }
}

Usage:

var customAttribute = GetAttributeCustom<MyClass>("MyMethod");
if (customAttribute != null)
{
    Console.WriteLine(customAttribute.MyPropertyAttribute);
}

Cast the object to MethodTestingAttibute:

object actual = method.Invoke(obj, null);

MethodTestingAttibute attribute = (MethodTestingAttibute)method.GetCustomAttributes(typeof(MethodTestAttribute), true)[0];
string expected = attribute.Value;

bool areEqual = string.Equals(expected, actual != null ? actual.ToString() : null, StringComparison.Ordinal);

Tags:

C#

Attributes