user2233219
user2233219

Reputation:

Is it possible to set a property as Enum but get a custom string value?

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?

Upvotes: 0

Views: 121

Answers (1)

41686d6564
41686d6564

Reputation: 19661

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
    <Description("Orange2")>
    Orange2 = 2
    <Description("Apple 1")>
    Apple1 = 3
End Enum

Now in a Module, add the following extension method:

<Runtime.CompilerServices.Extension>
Public Function GetEnumDescription(item As [Enum]) As String
    Return If(item.GetType().
                   GetField(item.ToString()).
                   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"

Upvotes: 2

Related Questions