locked
enum to convert int in c# MVC? RRS feed

  • Question

  • User-1933134441 posted

    How to int cast in enum in c#?

    Thursday, June 27, 2019 12:16 PM

Answers

All replies

  • User475983607 posted

    DevTeams

    How to int cast in enum in c#?

    I recommend going through the C# programming guide.

    https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/enumeration-types

    Example

    public enum Colors
    {
        Red,
        Green,
        Blue
    }

    Implementation

    int colorId = (int)Colors.Blue;

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, June 27, 2019 1:09 PM
  • User-821857111 posted

    int x = (int)MyEnum

    or the other way round:

    enum y = (MyEnum)x; 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, June 27, 2019 1:10 PM
  • User-1038772411 posted

    Hello DevTeams,

    Kindly refer the following links

    Every Enum is actually represented by an int per default. You should manually specify member values. By default it starts from 0 to N. It's also possible to cast Enum to string and vice versa.

    Reference 

    https://stackoverflow.com/questions/8899498/is-it-possible-to-cast-integer-to-enum/8899574#8899574

    https://stackoverflow.com/questions/29482/cast-int-to-enum-in-c-sharp/29485#29485

    Thank You

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, June 27, 2019 1:27 PM
  • User1520731567 posted

    Hi DevTeams,

    Enum provides a base class for enumerations whose base type can be any integer other than Char.

    Use Int32 if the underlying type is not explicitly declared.

    A programming language usually provides a syntax to declare an enumeration consisting of a set of named constants and their values.

    Note: The base type of an enumerated type is any integer other than Char, so the value of the enumerated type is an integer value.

    So,we just add strong type to convert,for example:

    public enum Colors { Red, Green, Blue, Yellow };
    Enum-->Int
    (int)Colors.Red //return 0
    Int-->Enum
    Colors color = (Colors)2 //color:Colors.Blue

    If convert to string,you could use static function:

    String-->Enum

    public static Object Parse(Type enumType,string value)

    (Colors)Enum.Parse(typeof(Colors), "Red")

    in addition,A method to determine if an integer is defined in an enumeration: Enum.IsDefined:

    public static bool IsDefined(Type enumType,Object value)
    
    Enum.IsDefined(typeof(Colors), n))

    Best Regards.

    Yuki Tao

    Friday, June 28, 2019 6:29 AM