How to cast int to enum and vice versa in C#

In C#, you can cast an integer to an enum and vice versa by explicitly converting them. Check these simple code examples:

  1. Casting an int to an enum:

    Suppose you have an enum like this:

    public enum Color
    {
        Red=1,
        Green=2,
        Blue=3
    }
    

    And you have an integer value:

    int intValue = 2; // representing Green
    

    You can cast this integer to the Color enum like this:

    Color colorValue = (Color)intValue;
    

    Now, colorValue will hold the value Color.Green.

  2. Casting an enum to an int:

    Similarly, if you have an enum value:

    Color colorValue = Color.Blue;
    

    You can cast this enum to an integer like this:

    int intValue = (int)colorValue;
    

    Now, intValue will hold the value 3.

It's straightforward, but it's essential to make sure that the integer value you're casting to or from an enum is within the range of the enum values, or else you might run into unexpected behavior.

 
Asp.Net Ajax Control Toolkit tutorials.

Give your valuable comments.

Name
Email
Comment
8 + 6 =
 

About Us | Terms of Use | Privacy Policy | Disclaimer | Contact Us Copyright © 2012-2024 CodingFusion
50+ C# Programs for beginners to practice