Enum
Apparence
Bases
enum MyEnum { Un = 1, Deux = 2 }
// Compter le nombre d’élément d’une énumération.
int count = Enum.GetValues(typeof(MyEnum)).Length;
// Retrieves the name of the constant that has the specified value.
Enum.GetName(typeof(MyEnum), 1); // → "Un"
// Get the name of the constant.
MyEnum.Un.ToString(); // "Un"
// Liste des noms des éléments de l'énumération.
Enum.GetNames(typeof(MyEnum)); // → "Un" | "Deux"
// Liste des valeurs de l'énumération.
Enum.GetValues(typeof(MyEnum)); // → MyEnum.Un | MyEnum.Deux
|
Convertions
int / byte
byte unEntier = 1;
MyEnum myEnum = (MyEnum)unEntier; // Deux
byte unEntier = (byte)MyEnum.Deux; // 1
|
string
// Parser un string en enum. Génère un ArgumentException en cas d'échec.
MyEnum myEnum = (MyEnum)Enum.Parse(typeof(MyEnum), "un", true);
// 3ème arg: IgnoreCase
if (Enum.TryParse("un", true, out MyEnum myEnum)) { }
|
Flags
[Flags]
public enum Font {
Bold = 1, // 1
Italic = 1 << 1, // 2
Underlined = 1 << 2, // 4
All = Bold | Italic | Underlined
}
// gras et italique
Font font = Font.Bold | Font.Italic;
// ajout de souligné
font |= Font.Underlined;
// suppression de souligné
font &= ~Font.Underlined;
// test si font contient Underlined
if (font.HasFlag(Font.Underlined)) { }
if ((font & Font.Underlined) == Font.Underlined) { }
Console.WriteLine(Font.Bold | Font.Italic | Font.Underlined); // All
|
Default value
int i = default(MyEnum);
// retourne toujours 0, même si 0 n'est pas une valeur valide
|
Description
var name = MyEnum.Un.ToString(); // Un
var description = MyEnum.Un.GetDisplayName(); // Un !
var description = EnumExtension.GetDisplayName(typeof(MyEnum), 1); // Un !
enum MyEnum
{
[Description("Un !")]
Un = 1,
[Description("Deux !")]
Deux = 2
}
public static class EnumExtension
{
// extension method
public static string GetDisplayName(this Enum source)
{
var enumType = source.GetType();
var name = Enum.GetName(enumType, source);
var fieldInfo = enumType.GetField(name);
var attributes = fieldInfo.GetCustomAttributes<DescriptionAttribute>();
return attributes.SingleOrDefault()?.Description ?? name;
}
// static method
public static string GetDisplayName(Type enumType, object value)
{
var name = Enum.GetName(enumType, value);
var fieldInfo = enumType.GetField(name);
var attributes = fieldInfo.GetCustomAttributes<DescriptionAttribute>();
return attributes.SingleOrDefault()?.Description ?? name;
}
}
|
Parse string values to enum values
public static bool TryParse<T>(IReadOnlyCollection<string> values, out T[] results)
where T : struct
{
if (values == null)
{
throw new ArgumentNullException(nameof(values));
}
results = new T[values.Count];
var i = 0;
foreach (var value in values)
{
if (Enum.TryParse(value, out T result))
{
results[i++] = result;
}
else
{
results = null;
return false;
}
}
return true;
}
|
Parse string value matching Attribute to enum value
public static bool TryParse<TEnum, TAttribute>(
string value,
Func<TAttribute, string> attributePropertySelector,
out TEnum result)
where TEnum : struct
{
var matchingField = typeof(TEnum).GetFields()
.SelectMany(
f => (IEnumerable<TAttribute>)f.GetCustomAttributes(typeof(TAttribute)),
(f, a) => new { Field = f, Attribute = a })
.Where(x => attributePropertySelector(x.Attribute) == value)
.Select(x => x.Field)
.SingleOrDefault();
result = matchingField == null ? default : (TEnum)matchingField.GetRawConstantValue();
return matchingField != null;
}
if (EnumExtension.TryParse<MyEnum, DescriptionAttribute>("Un !", x => x.Description, out MyEnum e)) { }
|