Generics: awesome (until you use enums)
Right, first up I think I should make it very clear that Generics in .NET 2.0 rock seriously hard. However, I feel in the intrests of developer awareness I should post this slight problem I found while writing a generic method a few days ago.
Basically, I was trying to write a method which could be called to get module settings from a database. I thought it would be a good idea to have one method that just picked up the setting. In this case, it was always coming from XML and so was a string when initially returned. It then returned it to me in the correct format.
Here's what I came up with initially:
Public Shared Function GetTabModuleSetting(Of T)(ByVal settings As Hashtable, ByVal key As String, ByVal DefaultValue As T) As T
Dim o As Object = settings(key)
Dim retValue As T = DefaultValue
If o IsNot Nothing Then
Try
retValue = Convert.ChangeType(o, GetType(T))
Catch ex As Exception
retValue = DefaultValue
End Try
End If
Return retValue
End FunctionPretty simple and works so long as the representation of the setting is convertable however enums return as their numeric values which is then in turn held in a string when returned to my function which will therefore not happily convert to a return type of Enum.The way I got round this is shown below:
Try
' If we are trying to return an enum then we have to work differently
If GetType(T).IsSubclassOf(GetType([Enum])) Then
retValue = Convert.ChangeType([Enum].Parse(GetType(T), [Enum].GetName(GetType(T), CType(o, Integer))), GetType(T))
Else
retValue = Convert.ChangeType(o, GetType(T))
End If
Catch ex As Exception
retValue = DefaultValue
End TryThis basically parses the enum correctly having initially converted the string representation of the numeric value into an integer. Not a pretty work around but a necessary one in order to make the function truely generic so as to include Enums in it's repertoire.

0 Comments:
Post a Comment
<< Home