Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I know others have already answered with a correct answer, however, if you're wanting to use the enumerations in a combo box, you may want to go the extra yard and associate strings to the enum so that you can provide more detail in the displayed string (such as spaces between words or display strings using casing that doesn't match your coding standards)</p> <p>This blog entry may be useful - <a href="http://blog.spontaneouspublicity.com/2008/01/17/associating-strings-with-enums-in-c/" rel="noreferrer">Associating Strings with enums in c#</a></p> <pre><code>public enum States { California, [Description("New Mexico")] NewMexico, [Description("New York")] NewYork, [Description("South Carolina")] SouthCarolina, Tennessee, Washington } </code></pre> <p>As a bonus, he also supplied a utility method for enumerating the enumeration that I've now updated with Jon Skeet's comments</p> <pre><code>public static IEnumerable&lt;T&gt; EnumToList&lt;T&gt;() where T : struct { Type enumType = typeof(T); // Can't use generic type constraints on value types, // so have to do check like this if (enumType.BaseType != typeof(Enum)) throw new ArgumentException("T must be of type System.Enum"); Array enumValArray = Enum.GetValues(enumType); List&lt;T&gt; enumValList = new List&lt;T&gt;(); foreach (T val in enumValArray) { enumValList.Add(val.ToString()); } return enumValList; } </code></pre> <p>Jon also pointed out that in C# 3.0 it can be simplified to something like this (which is now getting so light-weight that I'd imagine you could just do it in-line):</p> <pre><code>public static IEnumerable&lt;T&gt; EnumToList&lt;T&gt;() where T : struct { return Enum.GetValues(typeof(T)).Cast&lt;T&gt;(); } // Using above method statesComboBox.Items = EnumToList&lt;States&gt;(); // Inline statesComboBox.Items = Enum.GetValues(typeof(States)).Cast&lt;States&gt;(); </code></pre>
 

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