Today a friend of mine asked me how to define enums containing white spaces, after my initial response (”Why the *** you want to do that?”) i ended up with this code that demonstrates how 'flexible' is .NET (in this case using VB but, as you know, language is just a detail...)
Created a custom attribute...
<AttributeUsage(AttributeTargets.Field)> _
Public NotInheritable Class EnumDisplay : Inherits Attribute
Private mText As String
Public Sub New(ByVal text As String)
mText = text
End Sub
Public ReadOnly Property Text() As String
Get
Return mText
End Get
End Property
End Class
...and a simple helper function that uses both Generics and Reflection...
Public Class EnumHelper
Public Shared Function EnumToString(Of T As Structure)(ByVal value As T) As String
Dim sourceEnum As Type = value.GetType()
Dim name As String = [Enum].GetName(sourceEnum, value)
Dim fi As FieldInfo = sourceEnum.GetField(name)
Dim att As EnumDisplay = TryCast(Attribute.GetCustomAttribute(fi, GetType(EnumDisplay)), EnumDisplay)
If (att IsNot Nothing) Then Return att.Text
Return name
End Function
End Class
Now you can define your own Enum and decorate it with EnumDisplay where needed...
Public Enum TempState
Low
Middle
<EnumDisplay("Hi Temperature")> HiTemperature
TooHigh
End Enum
And get a string representation of enum field using:
Console.WriteLine(EnumHelper.EnumToString(TempState.HiTemperature)) ' Hi Temperature
Cool!