I'm trying to return a strongly typed Enumeration value from a string. I'm sure there is a better way to do this. This just seems like way too much code for a simple thing like this:
public static DeviceType DefaultDeviceType
{
get
{
var deviceTypeString = GetSetting("DefaultDeviceType");
if (deviceTypeString.Equals(DeviceType.IPhone.ToString()))
return DeviceType.IPhone;
if (deviceTypeString.Equals(DeviceType.Android.ToString()))
return DeviceType.Android;
if (deviceTypeString.Equals(DeviceType.BlackBerry.ToString()))
return DeviceType.BlackBerry;
if (deviceTypeString.Equals(DeviceType.Other.ToString()))
return DeviceType.Other;
return DeviceType.IPhone; // If no default is provided, use this default.
}
}
Ideas?
Based on the feedback I got from the community, I have decided to use a method extension that converts a string to an enumeration. It takes one parameter (the default enumeration value). That default also provides the type, so the generic can be inferred and doesn't need to be specified explicitly using <>. The method is now shortened to this:
public static DeviceType DefaultDeviceType
{
get
{
return GetSetting("DefaultDeviceType").ToEnum(DeviceType.IPhone);
}
}
Very cool solution that can be reused in the future.