22

I am trying to build an object through an attribute on a classes property that specifies a column in a supplied data row that is the value of the property, as below:

    [StoredDataValue("guid")]
    public string Guid { get; protected set; }

    [StoredDataValue("PrograGuid")]
    public string ProgramGuid { get; protected set; }

In a Build() method on a base object, I am getting the attribute values set on these properties as

        MemberInfo info = GetType();
        object[] properties = info.GetCustomAttributes(true);

However, at this point I am realising the limitation in my knowledge.

For a start, I don't appear to be getting back the correct attributes.

And how do I set these properties through reflection, now that I have the attributes? Am I doing / thinking something fundamentally incorrect?

johnc
  • 39,385
  • 37
  • 101
  • 139

1 Answers1

44

There are a couple of separate issues here

  • typeof(MyClass).GetCustomAttributes(bool) (or GetType().GetCustomAttributes(bool)) returns the attributes on the class itself, not the attributes on members. You will have to invoke typeof(MyClass).GetProperties() to get a list of properties in the class, and then check each of them.

  • Once you got the property, I think you should use Attribute.GetCustomAttribute() instead of MemberInfo.GetGustomAttributes() since you exactly know what attribute you are looking for.

Here's a little code snippet to help you start:

PropertyInfo[] properties = typeof(MyClass).GetProperties();
foreach(PropertyInfo property in properties)
{
    StoredDataValueAttribute attribute =
        Attribute.GetCustomAttribute(property, typeof(StoredDataValueAttribute)) as StoredDataValueAttribute;

    if (attribute != null) // This property has a StoredDataValueAttribute
    {
         property.SetValue(instanceOfMyClass, attribute.DataValue, null); // null means no indexes
    }
}

EDIT: Don't forget that Type.GetProperties() only returns public properties by default. You will have to use Type.GetProperties(BindingFlags) to get other sorts of properties as well.

Tamas Czinege
  • 118,853
  • 40
  • 150
  • 176
  • I'll give that a test and let you know, looks logical though – johnc Dec 24 '08 at 01:59
  • Attribute.GetCustomAttribute(...) returns an array of System.Attribute and cannot be simply cast to the attribute itself. The example shown does not even compile let alone work. You need to test the array length to see if the desired attribute exists and cast the first element to the required type instead. – iCollect.it Ltd Apr 17 '12 at 19:10
  • The example uses GetCustomAttribute, not GetCustomAttributes. The example compiles when I try it (of course, changing the attribute name). – Ricky Helgesson Jun 09 '12 at 13:23