This code simply takes an enum and converts its name to a string. For example, if you pass in
internal string ConvertEnumToString<T>(int val) where T : struct, IConvertible
retVal = Enum.GetValues(typeof(T))
.ToDictionary(t => Convert.ToInt32(t), t => t.ToString())[val];
retVal = "UNKNOWN";
Creating a dictionary of all enum values each time just to get one of them is an overkill. The following code will do what you need with much higher performance:
Function ConvertEnumToString(Of T)(value As Integer) As String Dim result As String = DirectCast(DirectCast(value, object), T).ToString() Return If(result = value.ToString(), "UNKNOWN", result) End Function
Code is tested.
1) In .NET it's not allowed to cast integer directly to generic type T, but we can first cast to object and then to any other type.
2) When not defined enum value is converted to string, the result is just a string representation of the corresponding integer value. Thus we use an additional check and replace integer representation with "UNKNOWN".