Here is an example of how you can cast an integer to an enum in C#:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public enum Season { Spring, Summer, Fall, Winter } int num = 2; Season season = (Season)num; console.WriteLine(season); // Output: Fall |
To cast an integer to an enum, you can use the Enum.ToObject
method:
1 2 3 4 5 6 | int num = 2; Season season = (Season)Enum.ToObject(typeof(Season), num); console.WriteLine(season); // Output: Fall |
Note that you need to be careful when casting between enums and integers, as the integer value of an enum member may not always be what you expect. It is generally a good idea to use the names of the enum members rather than their integer values in your code, to make it more readable and maintainable.
By default, the first member of an enum is assigned the value 0, and each subsequent member is assigned a value one greater than the previous member. However, you can specify custom values for enum members if you want:
1 2 3 4 5 6 7 8 9 | public enum Season { Spring = 3, Summer = 4, Fall = 5, Winter = 6 } |
You can also use the Enum.IsDefined
method to check if a particular integer value is a valid member of an enum:
1 2 3 4 5 6 7 8 | int num = 5; if (Enum.IsDefined(typeof(Season), num)) { Season season = (Season)num; Console.WriteLine(season); // Output: Fall } |
If you try to cast an integer value to an enum and the value is not a valid member of the enum, you will get an exception at runtime. To avoid this, you can use the Enum.TryParse
method, which tries to parse a string representation of an enum member and returns a boolean indicating whether the parse was successful:
1 2 3 4 5 6 7 | string input = "Summer"; if (Enum.TryParse<Season>(input, out Season season)) { Console.WriteLine(season); // Output: Summer } |