In The craft
Comparing Enums With the Same Values
Recently I came across some code where a switch statement was used to convert one Enum to another Enum. There were over 20 cases in the switch statement. The kicker was the values were the same. Why did they not use a single Enum? I’m still trying to figure that out.
I wrote some code that eliminated the massive switch statement:
public TTo MapEnum(TFrom from)
where TFrom : struct, IConvertible
where TTo : struct, IConvertible
{
System.Diagnostics.Contracts.Contract.Requires(!typeof(TTo).IsEnum, "TTo must be an enumerated type");
System.Diagnostics.Contracts.Contract.Requires(!typeof(TFrom).IsEnum, "TFrom must be an enumerated type");
string fromValue = Convert.ToString(from);
TTo toEnum;
bool found = Enum.TryParse(fromValue, true, out toEnum);
if (!found)
{
throw new Exception("Could not find value {0} for type {1} in enum {2} ");
}
return toEnum;
}