Casting Enums by using Extension Methods in C#.
Wednesday, June 23, 2010 8:39In C# there is no way to implicity cast one enum to another.
One possible way around this is by assigning values to each enum member. If the values of the first enum match the values of the second enum, you use two casts; the first casting the first enum value to an integer, and the second casts the integer to the second enum.
But this will only work if the values match, or if there is a function that you use to ‘calculate’ the second value.
If this is not possible, you can use Extension Methods to cast one enum to another.
Here is a generic example that uses two enum types. One is a custom ‘Day’ enum. The idea is that is should be possible to cast the custom ‘Day’ enum to the DayOfWeek enum, that is defined by default in C#. (I didn’t say this example was useful, but it’s the idea that counts.)
public enum Day { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, }
Now, we implement two custom extension methods. One on the Day enum AND one on the DayOfWeek enum to enable some sort of conversion;
public static class DayExtensions
{
public static DayOfWeek ToDayOfWeek(this Day day)
{
switch (day)
{
case Day.Friday: return DayOfWeek.Friday;
case Day.Monday: return DayOfWeek.Monday;
case Day.Saturday: return DayOfWeek.Saturday;
case Day.Sunday: return DayOfWeek.Sunday;
case Day.Thursday: return DayOfWeek.Thursday;
case Day.Tuesday: return DayOfWeek.Tuesday;
case Day.Wednesday: return DayOfWeek.Wednesday;
default: throw new ArgumentOutOfRangeException("day");
}
}
public static Day ToDay(this DayOfWeek day)
{
switch (day)
{
case DayOfWeek.Friday: return Day.Friday;
case DayOfWeek.Monday: return Day.Monday;
case DayOfWeek.Saturday: return Day.Saturday;
case DayOfWeek.Sunday: return Day.Sunday;
case DayOfWeek.Thursday: return Day.Thursday;
case DayOfWeek.Tuesday: return Day.Tuesday;
case DayOfWeek.Wednesday: return Day.Wednesday;
default: throw new ArgumentOutOfRangeException("day");
}
}
}
After creating these extension methods, you can use them as such;
Day day = DateTime.Now.DayOfWeek.ToDay();
DayOfWeek day = Day.Friday.ToDayOfWeek();
Have fun.
Leave a Reply
You must be logged in to post a comment.
