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?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With