How to use custom property attributes and get their values in C#

Lucio Flores
2020-10-23T03:44:04Z

Program.cs

| using System;
| using System.Reflection;
|
| namespace CustomPropertyAttributes
| {
| class Program
| {
| static void Main(string[] args)
| {
| var properties = typeof(ClientsExcelReport).GetProperties();
| foreach(var prop in properties)
| {
| Console.WriteLine($"Prop name: {prop.Name}");
| if(Attribute.IsDefined(prop, typeof(ExcelColumnNameAttribute)))
| Console.WriteLine(prop.GetCustomAttribute<ExcelColumnNameAttribute>().ColumnName);
| if (Attribute.IsDefined(prop, typeof(ExcelColumnCommentAttribute)))
| Console.WriteLine(prop.GetCustomAttribute<ExcelColumnCommentAttribute>().Comment);
| Console.WriteLine("**************");
| }
| }
| }
|
| class ClientsExcelReport
| {
| [ExcelColumnName("Nombre del cliente")]
| [ExcelColumnComment("Algun comentario tonto sobre la columna")]
| public string ClientName { get; set; }
| [ExcelColumnName("País")]
| public string ClientCountry { get; set; }
| [ExcelColumnName("Edad")]
| public string Age { get; set; }
| public string Status { get; set; }
| }
|
|
| public class ExcelColumnNameAttribute : Attribute
| {
| public ExcelColumnNameAttribute(string columnName)
| {
| ColumnName = columnName;
| }
|
| public string ColumnName { get; }
| }
|
| public class ExcelColumnCommentAttribute : Attribute
| {
| public ExcelColumnCommentAttribute(string comment)
| {
| Comment = comment;
| }
|
| public string Comment { get; }
| }
| }