Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store string descriptions of enumeration values?

The application I'm working on has lots of enumerations.

These values are generally selected from drop downs in the application.

What is the generally accepted way of storing the string description of these values?

Here is the current issue at hand:

Public Enum MyEnum
   SomeValue = 1
   AnotherValue = 2
   ObsoleteValue = 3
   YetAnotherValue = 4
End Enum

The drop down should have the following selections:

Some Value
Another Value
Yet Another Value (Minor Description)

Not all fit the name of the enumeration, (minor description on one is an example), and not all enumeration values are -current- values. Some remain only for backwards compatibility and display purposes (ie printouts, not forms).

This leads to the following code situation:

For index As Integer = 0 To StatusDescriptions.GetUpperBound(0)
   ' Only display relevant statuses.
   If Array.IndexOf(CurrentStatuses, index) >= 0 Then
      .Items.Add(New ExtendedListViewItem(StatusDescriptions(index), index))
   End If
Next

This just seems like it could be done better, and I'm not sure how.

like image 940
Brett Allen Avatar asked Dec 07 '22 02:12

Brett Allen


1 Answers

You could use the Description attribute (C# code, but it should translate):

public enum XmlValidationResult
{
    [Description("Success.")]
    Success,
    [Description("Could not load file.")]
    FileLoadError,
    [Description("Could not load schema.")]
    SchemaLoadError,
    [Description("Form XML did not pass schema validation.")]
    SchemaError
}

private string GetEnumDescription(Enum value)
{
    // Get the Description attribute value for the enum value
    FieldInfo fi = value.GetType().GetField(value.ToString());
    DescriptionAttribute[] attributes = 
        (DescriptionAttribute[])fi.GetCustomAttributes(
            typeof(DescriptionAttribute), false);

    if (attributes.Length > 0)
    {
        return attributes[0].Description;
    }
    else
    {
        return value.ToString();
    }
}

Source

like image 183
ChrisF Avatar answered Dec 09 '22 15:12

ChrisF