Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>TypeConverter. I think this is what I was looking for. All hail <a href="https://stackoverflow.com/questions/796607/how-do-i-override-tostring-in-c-enums/796675#796675">Simon Svensson</a>!</p> <pre><code>[TypeConverter(typeof(EnumToStringUsingDescription))] Enum HowNice { [Description("Really Nice")] ReallyNice, [Description("Kinda Nice")] SortOfNice, [Description("Not Nice At All")] NotNice } </code></pre> <p>All I need to change in my current enum is add this line before their declaration.</p> <pre><code>[TypeConverter(typeof(EnumToStringUsingDescription))] </code></pre> <p>Once I do that, any enum will get displayed using the <code>DescriptionAttribute</code> of its fields.</p> <p>Oh, and the <code>TypeConverter</code> would be defined like this:</p> <pre><code>public class EnumToStringUsingDescription : TypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { return (sourceType.Equals(typeof(Enum))); } public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { return (destinationType.Equals(typeof(String))); } public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { return base.ConvertFrom(context, culture, value); } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (!destinationType.Equals(typeof(String))) { throw new ArgumentException("Can only convert to string.", "destinationType"); } if (!value.GetType().BaseType.Equals(typeof(Enum))) { throw new ArgumentException("Can only convert an instance of enum.", "value"); } string name = value.ToString(); object[] attrs = value.GetType().GetField(name).GetCustomAttributes(typeof(DescriptionAttribute), false); return (attrs.Length &gt; 0) ? ((DescriptionAttribute)attrs[0]).Description : name; } } </code></pre> <p>This helps me with my ComboBox case, but obviously doesn't actually override the <code>ToString()</code>. I guess I'll settle for this meanwhile...</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload