Here you will learn how to convert Int to Enum in C#.
Convert int to Enum by Type Casting
You can explicitly type cast an int to a particular enum type, as shown below.
public enum Week
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
class Program
{
static void Main(string[] args)
{
int i = 2, j = 6, k = 10;
Week day1, day2, day3;
day1 = (Week)i; //Wednesday
day2 = (Week)j; //Sunday
day3 = (Week)k; //10
}
}
Convert int to Enum using Enum.ToObject() Method
Use the Enum.ToObject() method to convert integers to enum members, as shown below.
int i = 2, j = 6, k = 10;
Week day1, day2, day3;
day1 = (Week)Enum.ToObject(typeof(Week), i); //Wednesday
day2 = (Week)Enum.ToObject(typeof(Week), j); //Sunday
day3 = (Week)Enum.ToObject(typeof(Week), k); //10
Related Articles
- How to get the sizeof a datatype in C#?
- Difference between String and StringBuilder in C#
- Static vs Singleton in C#
- Difference between == and Equals() Method in C#
- Asynchronous programming with async, await, Task in C#
- How to loop through an enum in C#?
- Generate Random Numbers in C#
- Difference between Two Dates in C#
- BigInteger Data Type in C#
- Convert String to Enum in C#
- Convert an Object to JSON in C#
- Convert JSON String to Object in C#
- DateTime Formats in C#
- How to convert date object to string in C#?
- Compare strings in C#
- How to count elements in C# array?
- Difference between String and string in C#.
- How to get a comma separated string from an array in C#?
- Boxing and Unboxing in C#
- How to convert string to int in C#?