August 16, 2008

Enums

See this blog entry for information and example on the use of DescriptionAttribute with Enums

This example uses an ComboBox to store the enumeration values as strings Preparing the Combobox
foreach (XXXEnum entry in Enum.GetValues(typeof(XXXEnum)))
    comboBox.Items.Add(entry);
OR
cbLoggingLevel.Items.AddRange(Enum.GetValues(typeof(XXXEnum)));

// Making an initial selection
comboBox.SelectedIndex = comboBox.Items.Count - 1; // Select the last one
OR
comboBox.SelectedIndex = 0; // Select the first
Converting to and from a string
//To convert an enum to a string use:
MyComboBox.SelectedItem = m_Object.XXXEnum .ToString();

//The reverse process is a little more complicated
XXXEnum gc = (XXXEnum ) Enum.Parse(typeof(XXXEnum ),
                        MyComboBox.SelectedItem.ToString(), true);
There is a better way to parse the enum from a string that I found here.:
public static class StringExtender
{
  public static TEnum ParseToEnum<TEnum>(this string name)
    where TEnum : struct
  {
    if (false == typeof(TEnum).IsEnum)
      throw new NotSupportedException(typeof(TEnum).Name + " must be an Enum");

    string trimmed = name.Trim();
    
    if (false == Enum.IsDefined(typeof(TEnum), trimmed))
      throw new ArgumentException(string.Format(
         "\'{0}\' is not defined in type of enum {1}", trimmed, typeof(TEnum).Name));

    return (TEnum)Enum.Parse(typeof(TEnum), trimmed);
  }
}
alternatively use the TryParse method.
public class EnumTester
{
  public enum DescriptionsEnum
  {
    None,
    AddOn,
    SnapOn,
    Adjacent,
    Fixed,
  };

  public void ParseEnumFromStringTest()
  {
    DescriptionsEnum test = DescriptionsEnum.None;
    test = StringExtender.ParseToEnum<DescriptionsEnum>("Adjacent");
    Debug.Assert(test == DescriptionsEnum.Adjacent);
    test = "Fixed".ParseToEnum<DescriptionsEnum>();
    Debug.Assert(test == DescriptionsEnum.Fixed);
    test = "   SnapOn  ".ParseToEnum<DescriptionsEnum>();
    Debug.Assert(test == DescriptionsEnum.SnapOn);
    //test = "      snapon    ".ParseToEnum<DescriptionsEnum>(); // FAILS!
    //Debug.Assert(test == DescriptionsEnum.SnapOn);

    bool success = Enum.TryParse<DescriptionsEnum>("Adjacent", out test);
    Debug.Assert(test == DescriptionsEnum.Adjacent);
    success = Enum.TryParse<DescriptionsEnum>("fixed", true, out test);
    Debug.Assert(test == DescriptionsEnum.Fixed);
    success = Enum.TryParse<DescriptionsEnum>("  fixed     ", true, out test);
    // Line below succeeds. - TryParse is more robust so use it instead!
    Debug.Assert(test == DescriptionsEnum.Fixed); 
  }
}

Iterating through enumerated types:
foreach (XXXEnum entry in Enum.GetValues(typeof(XXXEnum)))
{
    Debug.WriteLine(entry.ToString() + "=" + ((int)entry).ToString());                
}
See Flags Based Enumerated Types

No comments: