Saturday, October 2, 2010

Handling Enumerations from a Web Service with Generic Functions

Looking back at some code I ran across a handy piece of code that I wrote to save a good deal of typing, increase maintainability and readability.

Dealing with enumerations from a web service can be confusing at first. The enumeration field names are the same on both sides (client and server) of the web service, however the values are likely not going to be the same. This is especially true if the enumeration is defined with specific values that don't start with 1. The client side will give the enumeration values starting with 1. This means that when saving the value back to a web service object with a property of the enumeration type, you must make sure that the correct enumeration value is returned.

We run into situations where the enumeration value needs to be resolved from enumeration field name and the enumeration field name needs to be resolved from a value. The to just handle this inline can be rather hard to read and requires duplicate typing. Generic functions to the rescue.

Public Shared Function ParseEnum(Of T)(ByVal value As String) As T
    Return CType(System.Enum.Parse(GetType(T), value, True), T)
End Function


Public Function ResolveEnumToValue(Of T)(ByVal value As Object) As String
    Dim genericType As Type = GetType(T)
    Return [Enum].GetName(genericType, value)
End Function

No comments: