views:

41

answers:

2

Am creating a custom attribute for my properties and was wondering if anyone know how i could access the the value of the Attribute inside of the get accessor.

public class MyClass
{
    [Guid("{2017ECDA-2B1B-45A9-A321-49EA70943F6D}")]
    public string MyProperty
    {
        get { return "value loaded from guid"; }
    }
}
+1  A: 

Setting aside the wisdom of such a thing...

public string MyProperty
{
    get
    {
        return this.GetType().GetProperty("MyProperty").GetCustomAttributes(typeof(GuidAttribute), true).OfType<GuidAttribute>().First().Value;
    }
}
Rex M
A: 

You can retrieve the property and then its custom attributes via reflection, like this:

// Get the property
my property = typeof(MyClass).GetProperty("MyProperty");

// Get the attributes of type “GuidAttribute”
my attributes = property.GetCustomAttributes(typeof(GuidAttribute), true);

// If there is an attribute of that type, return its value
if (attributes.Length > 0)
    return ((GuidAttribute) attributes[0]).Value;

// Otherwise, we’re out of luck!
return null;
Timwi