How can I convert int to enum in C # -e?

    2 answers 2

    From int :

     CustomEnum enm = (CustomEnum)number; 

    You can also:

     CustomEnum enm = (CustomEnum)Enum.ToObject(typeof(CustomEnum), number); 

    From string :

     CustomEnum enm = (CustomEnum)Enum.Parse(typeof(CustomEnum), str); 

      Before converting a number to an enumeration, you must check whether the number belongs to an enumeration in order not to go beyond the enum and not get unexpected code behavior due to an unexpected value:

       int number = 1; if (Enum.IsDefined(typeof(CustomEnum), number)) { CustomEnum enm = (CustomEnum)number; // преобразование // или CustomEnum enm = (CustomEnum)Enum.ToObject(typeof(CustomEnum), number); } 

      MSDN documentation:

      1. Enum.IsDefined
      2. enum (C # Reference)
      3. Enumeration Types (C # Programming Guide)
      4. Enum.TryParse

      From the MSDN documentation example:

       using System; [Flags] enum Colors { None=0, Red = 1, Green = 2, Blue = 4 }; public class Example { public static void Main() { string[] colorStrings = { "0", "2", "8", "blue", "Blue", "Yellow", "Red, Green" }; foreach (string colorString in colorStrings) { Colors colorValue; if (Enum.TryParse(colorString, out colorValue)) if (Enum.IsDefined(typeof(Colors), colorValue) | colorValue.ToString().Contains(",")) Console.WriteLine("Converted '{0}' to {1}.", colorString, colorValue.ToString()); else Console.WriteLine("{0} is not an underlying value of the Colors enumeration.", colorString); else Console.WriteLine("{0} is not a member of the Colors enumeration.", colorString); } } } // The example displays the following output: // Converted '0' to None. // Converted '2' to Green. // 8 is not an underlying value of the Colors enumeration. // blue is not a member of the Colors enumeration. // Converted 'Blue' to Blue. // Yellow is not a member of the Colors enumeration. // Converted 'Red, Green' to Red, Green. 

      In the example, the Enum.IsDefined check takes place. To protect your code from possible errors is not a sign of a bad programming tone, I think.

      • one
        In the overwhelming majority of living situations, this is absolutely superfluous and smacks of "Hinduism." The only exception is user input. - Sergey Rufanov
      • @SergeyRufanov, until a certain point, I also considered some checks unnecessary. But when potential errors appear in the code, this is not good. Of course, you cannot protect yourself against all mistakes, but some checks are worth doing. - Denis Bubnov
      • Nonsense. Exceptions when converting from the number do not crash : ideone.com/1EDWKg - Pavel Mayorov
      • @PavelMayorov, I agree. But instead of the expected word you will have a digit. Not nonsense, but a small reservation. Thanks, corrected. - Denis Bubnov
      • @PavelMayorov, regarding the exception - an exception may be thrown, for example, if a conversion from the string is in progress. Then we get an exception of the type Запрошенное значение "строка" не найдено . I considered a slightly wider range of applications for converting to enumeration, I don’t think it would be superfluous. - Denis Bubnov