Skip to content

Instantly share code, notes, and snippets.

@Lvcios
Created October 23, 2020 03:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Lvcios/2e460783e9b72e628b7f6da440f2a4ac to your computer and use it in GitHub Desktop.
Save Lvcios/2e460783e9b72e628b7f6da440f2a4ac to your computer and use it in GitHub Desktop.
How to use custom property attributes and get their values in C#
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; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment