Enum is a beautiful way to give a name to a number. It avoids to make some awkward things like public int constants (people from C/C++ know what I’m talking about).
But even senior developers had moments of doubts about how to make some conversions/operation using enums.
So this will be just some quick tips about this topic.
For instance, do you know if the ToString() of an Enum will return the number or the string with the name of the enum item?
using System; namespace Poc { class Program { static void Main(string[] args) { // ToString() of an Enum will return the description // in this case "Friday" Console.WriteLine(DayOfWeek.Friday.ToString()); // this will return the Enum number Console.WriteLine((int)DayOfWeek.Friday); var numberOfTheDayOfWeek = 5; Console.WriteLine(numberOfTheDayOfWeek.ToEnum<DayOfWeek>()); var stringOfTheDayOfWeek = "Friday"; Console.WriteLine(stringOfTheDayOfWeek.ToEnum<DayOfWeek>()); Console.ReadLine(); } } public static class EnumConversion { public static T ToEnum<T>(this string value) { return (T)Enum.Parse(typeof(T), value); } public static T ToEnum<T>(this int value) { return (T)Enum.ToObject(typeof(T), value); } } }
I hope it can be useful!
Spaki
2,552 thoughts on “C# enum”