4

When I try to get the custom attributes from an object the function returns null. Why?

class Person
{
    [ColumnName("first_name")]
    string FirstName { get; set; }

    Person()
    {
        FirstName = "not important";
        var attrs = AttributeReader.Read(FirstName);
    }
}

static class AttributeReader
{
    static object[] Read(object column)
    {
        return column.GetType().GetCustomAttributes(typeof(ColumnNameAttribute), false);
    }
}
3
  • did you try making FirstName public? Commented Jun 4, 2012 at 10:26
  • The code is only a generic example of what I am trying to do. Commented Jun 4, 2012 at 10:29
  • Don't you mean to call var attrs = AttributeReader.Read(Person);, not var attrs = AttributeReader.Read(FirstName); ? Commented Mar 28, 2013 at 13:27

1 Answer 1

14

You are passing a string, "not important" to that method. The Type is therefore typeof(string). Which does not have those attributes. Further, even Person doesn't have that attribute: only the MemberInfo (FirstName) has them.

There are ways of doing that by passing an Expression:

public static ColumnNameAttribute[] Read<T>(Expression<Func<T>> func)
{
    var member = func.Body as MemberExpression;
    if(member == null) throw new ArgumentException(
         "Lambda must resolve to a member");
    return (ColumnNameAttribute[])Attribute.GetCustomAttributes(
         member.Member, typeof(ColumnNameAttribute), false);
}

with

var attrs = AttributeReader.Read(() => FirstName);

However! I should advise that I'm not sure that the Person constructor is an appropriate place for this. Probably needs caching.

If you don't want to use lambdas, then passing a Type and the member-name would work too, i.e.

var attrs = AttributeReader.Read(typeof(Person), "FirstName");

(and do reflection from there) - or mixing with generics (for no real reason):

var attrs = Attribute.Read<Person>("FirstName");
Sign up to request clarification or add additional context in comments.

3 Comments

@Segfault my caveat still applies though: I personally wouldn't let that code anywhere near an object constructor - it is the wrong place for it.
Yeah, I was just trying to show what I was trying to do while making the code as clear as possible
How can I check if a particular attribute is required or not? I am creating an instance of a class as object obj = Activator.CreateInstance("myModel") and I need to check if a particular property is required or not: obj.GetType().GetProperty("prop1")........

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.