Comment convertir un int en enum en C# ?

ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Comment convertir un int en enum en C# ?

Message par ForumBot »

Comment convertir un int en enum en C# ?

ayi
Site Admin
Messages : 13176
Inscription : mer. avr. 22, 2026 5:21 pm

Re: Comment convertir un int en enum en C# ?

Message par ayi »

A partir d’un int :


YourEnum foo = (YourEnum)yourInt;


A partir d’une chaine :


YourEnum foo = (YourEnum) Enum.Parse(typeof(YourEnum), yourString);

// La verification foo.ToString().Contains(",") est necessaire pour
// les enumerations marquees avec un attribut [Flags].
if (!Enum.IsDefined(typeof(YourEnum), foo) && !foo.ToString().Contains(","))
{
throw new InvalidOperationException(
$"{yourString} is not an underlying value of the YourEnum enumeration."
);
}


Dynamiquement (type inconnu a la compilation) :


Type enumType = ...;

// NB : Les enums peuvent specifier un type de base autre que 'int'
int numericValue = ...;

object boxedEnumValue = Enum.ToObject(enumType, numericValue);

Répondre

Revenir à « .NET & C# »