Better comparison with enumeration
March 11th, 2008Suppose you have an enum list and a variable which value comes from external source. What do you usually do to compare against the enum list?
If (MyValue == "3") { //3 means ok, do some stuff }
What if one day you decide that you don’t like 3 (for whatever reason) and change it to 30? You will have to find and replace the repeated value all over your project. Yes, you have the FindAndReplace function with most IDE, but holy cow, you only realize that the last couple of 3 meant something else!
So a safer way is to cast the value into appropriate enum for comparison or any other operation.
'VB.NET
dim myEnumValue as TheEnum = CType([Enum].Parse(GetType(TheEnum), _
tempValue.ToString()), TheEnum)
If myEnumValue = TheEnum.NumberThree Then
'..
End If
//C#
TheEnum myEnumValue = (TheEnum)Enum.Parse(typeof(TheEnum), tempValue);
if (myEnumValue == TheEnum.NumberThree) { //.. }
“Hey, that looks useful. I want it in my SuperCoolReusable library” you might say. With the power of Generic, we can put it into a common call.
'VB.NET
Public Shared Function ParseEnum(Of T)(ByVal Value As Object) As T
Return CType([Enum].Parse(GetType(T), Value.ToString()), T)
End Function
//C#
public static ReturnType ConvertStringToEnum<ReturnType>(string Value)
{
return (ReturnType)Enum.Parse(typeof(ReturnType), Value);
}
Another simple yet useful tip! ![]()