using System.Collections.Generic;
public abstract class FieldNameAttribute : Attribute
public string FieldName { get; private set; }
public FieldNameAttribute(string fieldName)
public class SomeFieldNameAttribute : FieldNameAttribute
public SomeFieldNameAttribute(string fieldName) : base(fieldName) {}
public class OtherFieldNameAttribute : FieldNameAttribute
public OtherFieldNameAttribute(string fieldName) : base(fieldName) {}
[SomeFieldName("campo x")]
[OtherFieldName("campo1")]
[OtherFieldName("campo2")]
[SomeFieldName("campo z")]
[OtherFieldName("campo3")]
public static class FieldNameHelper
public static List<string> GetAllFieldNames<TEnum, TAttribute>()
where TAttribute : FieldNameAttribute
var fields = new List<string>();
foreach (TEnum t in Enum.GetValues(typeof(TEnum)))
var fieldName = t.GetFieldName<TAttribute>();
if (!string.IsNullOrEmpty(fieldName)) { fields.Add(fieldName); }
public static void Main()
var x = FieldNames.Field1;
Console.WriteLine($"{nameof(SomeFieldNameAttribute)} field names:");
FieldNameHelper.GetAllFieldNames<FieldNames, SomeFieldNameAttribute>().ForEach(x => Console.WriteLine(x));
Console.WriteLine($"\n{nameof(OtherFieldNameAttribute)} field names:");
FieldNameHelper.GetAllFieldNames<FieldNames, OtherFieldNameAttribute>().ForEach(x => Console.WriteLine(x));
public static class FieldNameExtensions
public static string GetFieldName<TAttribute>(this Enum value)
where TAttribute : Program.FieldNameAttribute
.GetField(value.ToString())
.GetCustomAttributes(typeof(TAttribute), false)
.FirstOrDefault() as TAttribute;
return attr != null ? attr.FieldName : string.Empty;