Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GetCustomAttributes does not return value

I have defined a custom attribute

[AttributeUsage(AttributeTargets.Property )]
public class FieldAttribute: Attribute
{
    public FieldAttribute(string field)
    {
        this.field = field;
    }
    private string field;

    public string Field
    {
        get { return field; }

    }
}

My Class which uses the custom attribute is as below

[Serializable()]   
public class DocumentMaster : DomainBase
{

    [Field("DOC_CODE")]
    public string DocumentCode { get; set; }


    [Field("DOC_NAME")]
    public string DocumentName { get; set; }


    [Field("REMARKS")]
    public string Remarks { get; set; }


   }
}

But when i try to get the value of the custom attribute it returns null object

Type typeOfT = typeof(T);
T obj = Activator.CreateInstance<T>();

PropertyInfo[] propInfo = typeOfT.GetProperties();

foreach (PropertyInfo property in propInfo)
{

     object[] colName = roperty.GetCustomAttributes(typeof(FieldAttributes), false);
     /// colName has no values.
}

What am I missing?

like image 734
user99322 Avatar asked Apr 25 '12 12:04

user99322


1 Answers

typo: should be typeof(FieldAttribute). There is an unrelated system enum called FieldAttributes (in System.Reflection, which you have in your using directives, since PropertyInfo resolves correctly).

Also, this is easier usage (assuming the attribute doesn't allow duplicates):

var field = (FieldAttribute) Attribute.GetCustomAttribute(
          property, typeof (FieldAttribute), false);
if(field != null) {
    Console.WriteLine(field.Field);
}
like image 80
Marc Gravell Avatar answered Oct 15 '22 19:10

Marc Gravell