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);
}
}
You are passing a
string,"not important"to that method. TheTypeis thereforetypeof(string). Which does not have those attributes. Further, evenPersondoesn’t have that attribute: only theMemberInfo(FirstName) has them.There are ways of doing that by passing an
Expression:with
However! I should advise that I’m not sure that the
Personconstructor is an appropriate place for this. Probably needs caching.If you don’t want to use lambdas, then passing a
Typeand the member-name would work too, i.e.(and do reflection from there) – or mixing with generics (for no real reason):