I'd like to set a property as an Enum so only certain values can be stored but when getting the property, I'd like to get a string value.

So for example, store an Enum of Orange1 but get "Orange 1".

Is this possible? If not, what would be the best way to achieve this?

1 Answers

Ahmed Abdelhameed On Best Solutions

One way would be to use a Description attribute. Let's create an Enum that looks like this:

Public Enum Fruit
    <Description("Orange 1")>
    Orange1 = 1
    Orange2 = 2
    <Description("Apple 1")>
    Apple1 = 3
End Enum

Now in a Module, add the following extension method:

Public Function GetEnumDescription(item As [Enum]) As String
    Return If(item.GetType().
                   GetCustomAttributes(GetType(DescriptionAttribute), False).
                   Cast(Of DescriptionAttribute)().
                   FirstOrDefault()?.Description, String.Empty)
End Function

Then, you can do something like this:

Dim f As Fruit = Fruit.Orange1
Console.WriteLine(f.GetEnumDescription())   ' Prints "Orange 1"