jueves, 22 de octubre de 2020

Using Custom Property Attributes in C#

 Hi, in this post I want to share what I learned just today.

Well, I had to create an excel file and that's very common right? The problem for me was that I couldn't use bad practices like put the column name as raw. The solution was pretty simple: Custom Attributes.

If you prefer it, you can go to the code:

https://gist.github.com/Lvcios/2e460783e9b72e628b7f6da440f2a4ac

 

If you are still here thanks. I'm not going to explain so much about System.Reflection which is the class that let us do this.

So, this is our row model and we are gonna use the custom attributes for the headers.

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; }
    }


Now, the attribute class for each attribute:

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; }
    }


Finally, the main function:


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("**************");
            }
        }