Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value from custom attribute-decorated property?

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?

like image 925
Joe Avatar asked Feb 03 '11 23:02

Joe


2 Answers

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();
like image 145
EvgK Avatar answered Oct 27 '22 05:10

EvgK


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

Call it this way:

var value = prop.GetValue(o, null);
like image 26
Andrey Avatar answered Oct 27 '22 07:10

Andrey