12

I've written a custom attribute that I use on certain members of a class:

public class Dummy
{
    [MyAttribute]
    public string Foo { get; set; }

    [MyAttribute]
    public int Bar { get; set; }
}

I'm able to get the custom attributes from the type and find my specific attribute. What I can't figure out how to do is to get the values of the assigned properties. When I take an instance of Dummy and pass it (as an object) to my method, how can I take the PropertyInfo object I get back from .GetProperties() and get the values assigned to .Foo and .Bar?

EDIT:

My problem is that I can't figure out how to properly call GetValue.

void TestMethod (object o)
{
    Type t = o.GetType();

    var props = t.GetProperties();
    foreach (var prop in props)
    {
        var propattr = prop.GetCustomAttributes(false);

        object attr = (from row in propattr where row.GetType() == typeof(MyAttribute) select row).First();
        if (attr == null)
            continue;

        MyAttribute myattr = (MyAttribute)attr;

        var value = prop.GetValue(prop, null);
    }
}

However, when I do this, the prop.GetValue call gives me a TargetException - Object does not match target type. How do I structure this call to get this value?

Joe
  • 41,484
  • 20
  • 104
  • 125

2 Answers2

12

Your need to pass object itself to GetValue, not a property object:

var value = prop.GetValue(o, null);

And one more thing - you should use not .First(), but .FirstOrDefault(), because your code will throw an exception, if some property does not contains any attributes:

object attr = (from row in propattr 
               where row.GetType() == typeof(MyAttribute) 
               select row)
              .FirstOrDefault();
Chris Marisic
  • 32,487
  • 24
  • 164
  • 258
EvgK
  • 1,907
  • 12
  • 10
  • Agreed on FirstOrDefault -- this is mostly a contrived example to demonstrate the problem, but thanks for the help. Duh, can't believe that was it. – Joe Feb 04 '11 at 12:06
3

You get array of PropertyInfo using .GetProperties() and call PropertyInfo.GetValue Method on each

Call it this way:

var value = prop.GetValue(o, null);
Andrey
  • 59,039
  • 12
  • 119
  • 163
  • To clarify; the OP will need an instance of the Dummy class in order to get a property value from it. A Type by itself isn't enough. – KeithS Feb 04 '11 at 00:36
  • I've updated my question -- my problem is exactly with .GetValue and how to call it so it actually works. – Joe Feb 04 '11 at 01:23