How can you enumerate an enum in C#?
E.g. the following code does not compile:
public enum Suit
{
I made some extensions for easy enum usage. Maybe someone can use it...
public static class EnumExtensions
{
///
/// Gets all items for an enum value.
///
///
/// The value.
///
public static IEnumerable GetAllItems(this Enum value)
{
foreach (object item in Enum.GetValues(typeof(T)))
{
yield return (T)item;
}
}
///
/// Gets all items for an enum type.
///
///
/// The value.
///
public static IEnumerable GetAllItems() where T : struct
{
foreach (object item in Enum.GetValues(typeof(T)))
{
yield return (T)item;
}
}
///
/// Gets all combined items from an enum value.
///
///
/// The value.
///
///
/// Displays ValueA and ValueB.
///
/// EnumExample dummy = EnumExample.Combi;
/// foreach (var item in dummy.GetAllSelectedItems())
/// {
/// Console.WriteLine(item);
/// }
///
///
public static IEnumerable GetAllSelectedItems(this Enum value)
{
int valueAsInt = Convert.ToInt32(value, CultureInfo.InvariantCulture);
foreach (object item in Enum.GetValues(typeof(T)))
{
int itemAsInt = Convert.ToInt32(item, CultureInfo.InvariantCulture);
if (itemAsInt == (valueAsInt & itemAsInt))
{
yield return (T)item;
}
}
}
///
/// Determines whether the enum value contains a specific value.
///
/// The value.
/// The request.
///
/// true if value contains the specified value; otherwise, false .
///
///
///
/// EnumExample dummy = EnumExample.Combi;
/// if (dummy.Contains(EnumExample.ValueA))
/// {
/// Console.WriteLine("dummy contains EnumExample.ValueA");
/// }
///
///
public static bool Contains(this Enum value, T request)
{
int valueAsInt = Convert.ToInt32(value, CultureInfo.InvariantCulture);
int requestAsInt = Convert.ToInt32(request, CultureInfo.InvariantCulture);
if (requestAsInt == (valueAsInt & requestAsInt))
{
return true;
}
return false;
}
}
The enum itself must be decorated with the FlagsAttribute:
[Flags]
public enum EnumExample
{
ValueA = 1,
ValueB = 2,
ValueC = 4,
ValueD = 8,
Combi = ValueA | ValueB
}