Loading ...

C# Casting with ENUM | CodeAsp.Net

C#: Casting with ENUM

 /5
0 (0votes)

In this blog I will show how to cast an int to enum, enum to int and string to enum. Let's make a sample enum:
MyEnum.cs

namespace Sample.Console
{
    public enum MyEnum
    {
        Item1 = 1,
        Item2 = 2,
        Item3 = 3,
        Item4 = 4,
        Item5 = 5,
    }
}


1. Int to Enum

            int integerValue = 2;
            MyEnum myenum = (MyEnum)integerValue;
            //Output: item2

2. Enum to Int

            MyEnum myenum = MyEnum.Item3;
            int integerValue = (int)myenum;
            //Output: 3


3. String to Enum

            string str = "Item4";
            MyEnum myenum = (MyEnum)Enum.Parse(typeof(MyEnum), str);
            //Output: Item4 Enum


 

Comments (no comments yet)

Top Posts