Home c# convert int in enum

convert int in enum




How can you convert int in enum in C # -e?

Answer 1, Authority 100%

from int :


you can also:

customenum enm = (customenum) enum.ToObject (Typeof (CustomENUM), NUMBER);

from String :

customenum enm = (customenum) enum.parse (Typeof (CustomENUM), STR);

Answer 2, Authority 46%

Before converting a number in the listing, it is necessary to check whether the number of listing belongs to not exit the ENUM and not to receive unexpected code for the code due to an unforeseen value:

int number = 1;
If (Enum.Isdefined (Typeof (CustomEnum), Number))
  CustomENUM ENM = (CustomENUM) Number; // Transformation
  // or 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 example of documentation on MSDN:

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 ());
        Console.WriteLine ("{0} is not an underlying value of the colors enumeration.", ColorString);
      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 occurs. Musture your code from possible errors – is not a sign of bad programming tone, I think so.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions