# VBForums CodeBank > CodeBank - Visual Basic .NET >  Enum to represent String constants

## Pradeep1210

Enumerations are basically used to represent numeric constants. But many a times I have felt the need of my enumerations to represent string constants.
Here is one way of how to make this possible. This makes use of the capabilities of the *System.ComponentModel* namespace.

This is how you define the enum:
(Notice the Description metadata attribute contains the string value we want for the enum)


vb.net Code:
''Put the string value of your enum in the Description metatag.'' (Dont forget to Import System.ComponentModel)Public Enum GMCars    <Description("Chevy SRV")> ChevySRV     <Description("Chevrolet aveo")> ChevroletAveo     <Description("Chevrolet Optra")> ChevroletOptra     <Description("Chevrolet Opel GT")> ChevroletOpelGT     <Description("Chevrolet Magnum Optra")> ChevroletMagnumOptra     <Description("Chevrolet Tavera")> ChevroletTavera     <Description("Chevrolet Tavera Neo")> ChevroletTaveraNeo     <Description("Chevrolet aveo U-VA")> ChevroletAveoUVA     <Description("Opel Astra")> OpelAstra     <Description("Opel Corsa")> OpelCorsa     <Description("Opel Corsa Swing")> OpelCorsaSwing     <Description("Chevrolet Captiva ")> ChevroletCaptiva     <Description("Chevrolet Malibu ")> ChevroletMalibu End Enum


Now put this function in any module, so that it is accessible through the application:


vb.net Code:
''This procedure gets the <Description> attribute of an enum constant, if any.''Otherwise it gets the string name of the enum member.Public Shared Function EnumDescription(ByVal EnumConstant As [Enum]) As String    Dim fi As Reflection.FieldInfo = EnumConstant.GetType().GetField(EnumConstant.ToString())    Dim aattr() As DescriptionAttribute = DirectCast(fi.GetCustomAttributes(GetType(DescriptionAttribute), False), DescriptionAttribute())    If aattr.Length > 0 Then        Return aattr(0).Description    Else        Return EnumConstant.ToString()    End IfEnd Function

OK so now we are ready to use our setup with string values.
Now each enum member contains a string value attached with it and we can get it using our EnumDescription function wherever we want the String value. Otherwise we would use it as we would use any other enum which represents numeric constants.

Let’s fill it into a listbox for example:

vb.net Code:
ListBox1.Items.Add(EnumDescription(GMCars.ChevySRV))ListBox1.Items.Add(EnumDescription(GMCars.ChevroletOptra))ListBox1.Items.Add(EnumDescription(GMCars.ChevroletOpelGT))ListBox1.Items.Add(EnumDescription(GMCars.ChevroletAveoUVA))ListBox1.Items.Add(EnumDescription(GMCars.OpelAstra))

Note that we no longer need to type the actual string values, but instead use the Enum members.

The advantage you get with this method is the same as what you get with normal enums that represent numbers. You do not have to type the actual numeric value wherever you use it. Same way you do not need to type the String values in this case wherever you use this enum.

In the above code sample I have used the procedure name "EnumDescription" to explain things here better, that makes the code lines look longer. But in actual practice I use very short notation (e.g. ED) so that it is hardly noticable. So the code line reduces to something like:

vb.net Code:
ListBox1.Items.Add(ED(GMCars.ChevySRV))

Really easy. Isn't it?  :Wink: 

Pradeep  :Smilie:

----------


## Pradeep1210

Optionally, we could also put a numeric value if required and we can have an enum that has string representation as well as numeric representation too.


vb.net Code:
''Put the string value of your enum in the Description metatag.''You may optionally provide a numeric value too.Public Enum GMCars    <Description("Chevy SRV")> ChevySRV = 1    <Description("Chevrolet aveo")> ChevroletAveo = 2    <Description("Chevrolet Optra")> ChevroletOptra = 3    <Description("Chevrolet Opel GT")> ChevroletOpelGT = 4    <Description("Chevrolet Magnum Optra")> ChevroletMagnumOptra = 5    <Description("Chevrolet Tavera")> ChevroletTavera = 6    <Description("Chevrolet Tavera Neo")> ChevroletTaveraNeo = 7    <Description("Chevrolet aveo U-VA")> ChevroletAveoUVA = 8    <Description("Opel Astra")> OpelAstra = 9    <Description("Opel Corsa")> OpelCorsa = 10    <Description("Opel Corsa Swing")> OpelCorsaSwing = 11    <Description("Chevrolet Captiva ")> ChevroletCaptiva = 12    <Description("Chevrolet Malibu ")> ChevroletMalibu = 13End Enum

----------


## Pradeep1210

Today I tried the same thing with extensions. It works great and a pair of brackets less to deal with. So looks more professional  :Big Grin:  


vb.net Code:
Imports System.Runtime.CompilerServices Public Module MyExtensions    ''This procedure gets the <Description> attribute of an enum constant, if any.    ''Otherwise it gets the string name of the enum member.    <Extension()> _    Public Function Description(ByVal EnumConstant As [Enum]) As String        Dim fi As Reflection.FieldInfo = EnumConstant.GetType().GetField(EnumConstant.ToString())        Dim aattr() As DescriptionAttribute = DirectCast(fi.GetCustomAttributes(GetType(DescriptionAttribute), False), DescriptionAttribute())        If aattr.Length > 0 Then            Return aattr(0).Description        Else            Return EnumConstant.ToString()        End If    End FunctionEnd Module

So now we can do the equivalent of what I was doing in post #1 with normal method like this:

vb.net Code:
ListBox1.Items.Add(GMCars.ChevySRV.Description)ListBox1.Items.Add(GMCars.ChevroletOptra.Description)ListBox1.Items.Add(GMCars.ChevroletOpelGT.Description)ListBox1.Items.Add(GMCars.ChevroletAveoUVA.Description)ListBox1.Items.Add(GMCars.OpelAstra.Description)

Well done Pradeep  :Stick Out Tongue:

----------


## jmcilhinney

http://www.vbforums.com/showthread.php?t=552547  :Smilie: 

I like the extension method, although it's worth mentioning that they are only available in .NET 3.5, for those who aren't aware.

----------


## Pradeep1210

Hey jm.. that's a nice article. 
I was playing around with it at the ground level, but you took it one step higher and got to a purely OOP one. So that code is much more advanced than mine.  :Thumb:

----------


## Pradeep1210

And I completely missed the databinding part. So anyone using my code and struggling to databind it to combobox, listbox or any other such control, here's how I'm doing it.

(uses LINQ, only available in .NET 3.5; but a non-LINQ version should be easy to construct) 

vb.net Code:
Public Shared Sub BindObjectToEnum(ByRef TargetControl As Object, ByVal SourceEnum As System.Type)
    Dim selection = From item In [Enum].GetValues(SourceEnum) _
                    Select New With {.Text = EnumDescription([Enum].ToObject(SourceEnum, item)), _
                                     .Value = CInt(item)}
    With TargetControl
        .DisplayMember = "Text"
        .ValueMember = "Value"
        .DataSource = selection.ToList
    End With
End Sub

Usage:

vb.net Code:
BindObjectToEnum(MyListBox, GetType(GMCars))


Pradeep  :Smilie:

----------


## Tms72

Hi Dear
This code is very helpful but i have a question
What i can do if i need to filter the combobox with textbox_textchange and update the list. 
Thanks

----------


## jmcilhinney

> Hi Dear
> This code is very helpful but i have a question
> What i can do if i need to filter the combobox with textbox_textchange and update the list. 
> Thanks


If you want to filter the list you already have then that has nothing to do with the topic of this thread.  Once you have a list of objects with properties, how you use that list and those objects has nothing to do with how you got them.  If you don't mind creating a new list (note that changing the list bound to a ComboBox will clear the current selection and select the first item) then you can use the same LINQ query from post #6 with a Where clause, e.g.

vb.net Code:
Dim selection = From item In [Enum].GetValues(SourceEnum)                Let description = EnumDescription([Enum].ToObject(SourceEnum, item))                Where description.Contains(someText)                Select New With {.Text = description,                                 .Value = CInt(item)}

----------

