I\'ve heard some people saying that enums are evil and shouldn\'t be used in web services because of the mismatches that could occur between the server and the client if som
Here's an approach. Maybe it's cumbersome. I just really dislike not being able to use enums.
It gracefully handles deserialization of an unrecognized value, returning the default value instead. The default value would need to be safe - either an acceptable fallback or something that the application could recognize as exceptional. (Like "Unspecified.")
The extensions prevent having to null-check before comparing.
[DataContract]
public class EnumValue where T : struct
{
[DataMember]
private string _raw = string.Empty;
[IgnoreDataMember]
private bool _parsed;
[IgnoreDataMember]
private T _parsedValue;
public EnumValue()
{
Set(default(T));
}
public EnumValue(T value)
{
Set(value);
}
internal T Value
{
get
{
if (_parsed) return _parsedValue;
if (!Enum.TryParse(_raw, out _parsedValue))
{
_parsedValue = default(T);
}
_parsed = true;
return _parsedValue;
}
}
public void Set(T value)
{
_raw = value.ToString();
_parsedValue = value;
_parsed = true;
}
}
public static class EnumValueExtensions
{
public static T GetValue(this EnumValue enumValue) where T : struct
{
return enumValue == null ? default(T) : enumValue.Value;
}
public static bool EqualsValue(this EnumValue enumValue, T compareTo) where T : struct
{
return (enumValue.GetValue().Equals(compareTo));
}
}