PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197

PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197

PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197

PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197

PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197

PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197

PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197

PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197

PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197

PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197
Enum to represent String constants-VBForums
Results 1 to 8 of 8

Thread: Enum to represent String constants

  1. #1

    Thread Starter
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,612

    Enum to represent String constants

    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:
    1. ''Put the string value of your enum in the Description metatag.
    2. '' (Dont forget to Import System.ComponentModel)
    3. Public Enum GMCars
    4.     <Description("Chevy SRV")> ChevySRV
    5.     <Description("Chevrolet aveo")> ChevroletAveo
    6.     <Description("Chevrolet Optra")> ChevroletOptra
    7.     <Description("Chevrolet Opel GT")> ChevroletOpelGT
    8.     <Description("Chevrolet Magnum Optra")> ChevroletMagnumOptra
    9.     <Description("Chevrolet Tavera")> ChevroletTavera
    10.     <Description("Chevrolet Tavera Neo")> ChevroletTaveraNeo
    11.     <Description("Chevrolet aveo U-VA")> ChevroletAveoUVA
    12.     <Description("Opel Astra")> OpelAstra
    13.     <Description("Opel Corsa")> OpelCorsa
    14.     <Description("Opel Corsa Swing")> OpelCorsaSwing
    15.     <Description("Chevrolet Captiva ")> ChevroletCaptiva
    16.     <Description("Chevrolet Malibu ")> ChevroletMalibu
    17. End Enum


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

    vb.net Code:
    1. ''This procedure gets the <Description> attribute of an enum constant, if any.
    2. ''Otherwise it gets the string name of the enum member.
    3. Public Shared Function EnumDescription(ByVal EnumConstant As [Enum]) As String
    4.     Dim fi As Reflection.FieldInfo = EnumConstant.GetType().GetField(EnumConstant.ToString())
    5.     Dim aattr() As DescriptionAttribute = DirectCast(fi.GetCustomAttributes(GetType(DescriptionAttribute), False), DescriptionAttribute())
    6.     If aattr.Length > 0 Then
    7.         Return aattr(0).Description
    8.     Else
    9.         Return EnumConstant.ToString()
    10.     End If
    11. End 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:
    1. ListBox1.Items.Add(EnumDescription(GMCars.ChevySRV))
    2. ListBox1.Items.Add(EnumDescription(GMCars.ChevroletOptra))
    3. ListBox1.Items.Add(EnumDescription(GMCars.ChevroletOpelGT))
    4. ListBox1.Items.Add(EnumDescription(GMCars.ChevroletAveoUVA))
    5. 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:
    1. ListBox1.Items.Add(ED(GMCars.ChevySRV))

    Really easy. Isn't it?

    Pradeep
    Last edited by Pradeep1210; Apr 8th, 2009 at 10:31 AM.
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." Charles F. Kettering

    Read articles on My Blog 101 LINQ Samples JSON Validator XML Schema Validator "How Do I" videos on MSDN VB.NET and C# Comparison Good Coding Practices VBForums Reputation Saver String Enum Super Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  2. #2

    Thread Starter
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,612

    Re: Enum to represent String constants

    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:
    1. ''Put the string value of your enum in the Description metatag.
    2. ''You may optionally provide a numeric value too.
    3. Public Enum GMCars
    4.     <Description("Chevy SRV")> ChevySRV = 1
    5.     <Description("Chevrolet aveo")> ChevroletAveo = 2
    6.     <Description("Chevrolet Optra")> ChevroletOptra = 3
    7.     <Description("Chevrolet Opel GT")> ChevroletOpelGT = 4
    8.     <Description("Chevrolet Magnum Optra")> ChevroletMagnumOptra = 5
    9.     <Description("Chevrolet Tavera")> ChevroletTavera = 6
    10.     <Description("Chevrolet Tavera Neo")> ChevroletTaveraNeo = 7
    11.     <Description("Chevrolet aveo U-VA")> ChevroletAveoUVA = 8
    12.     <Description("Opel Astra")> OpelAstra = 9
    13.     <Description("Opel Corsa")> OpelCorsa = 10
    14.     <Description("Opel Corsa Swing")> OpelCorsaSwing = 11
    15.     <Description("Chevrolet Captiva ")> ChevroletCaptiva = 12
    16.     <Description("Chevrolet Malibu ")> ChevroletMalibu = 13
    17. End Enum
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." Charles F. Kettering

    Read articles on My Blog 101 LINQ Samples JSON Validator XML Schema Validator "How Do I" videos on MSDN VB.NET and C# Comparison Good Coding Practices VBForums Reputation Saver String Enum Super Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  3. #3

    Thread Starter
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,612

    Re: Enum to represent String constants

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

    vb.net Code:
    1. Imports System.Runtime.CompilerServices
    2.  
    3. Public Module MyExtensions
    4.     ''This procedure gets the <Description> attribute of an enum constant, if any.
    5.     ''Otherwise it gets the string name of the enum member.
    6.     <Extension()> _
    7.     Public Function Description(ByVal EnumConstant As [Enum]) As String
    8.         Dim fi As Reflection.FieldInfo = EnumConstant.GetType().GetField(EnumConstant.ToString())
    9.         Dim aattr() As DescriptionAttribute = DirectCast(fi.GetCustomAttributes(GetType(DescriptionAttribute), False), DescriptionAttribute())
    10.         If aattr.Length > 0 Then
    11.             Return aattr(0).Description
    12.         Else
    13.             Return EnumConstant.ToString()
    14.         End If
    15.     End Function
    16. End Module

    So now we can do the equivalent of what I was doing in post #1 with normal method like this:
    vb.net Code:
    1. ListBox1.Items.Add(GMCars.ChevySRV.Description)
    2. ListBox1.Items.Add(GMCars.ChevroletOptra.Description)
    3. ListBox1.Items.Add(GMCars.ChevroletOpelGT.Description)
    4. ListBox1.Items.Add(GMCars.ChevroletAveoUVA.Description)
    5. ListBox1.Items.Add(GMCars.OpelAstra.Description)

    Well done Pradeep
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." Charles F. Kettering

    Read articles on My Blog 101 LINQ Samples JSON Validator XML Schema Validator "How Do I" videos on MSDN VB.NET and C# Comparison Good Coding Practices VBForums Reputation Saver String Enum Super Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  4. #4
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    102,920

    Re: Enum to represent String constants

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

    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.

  5. #5

    Thread Starter
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,612

    Re: Enum to represent String constants

    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.
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." Charles F. Kettering

    Read articles on My Blog 101 LINQ Samples JSON Validator XML Schema Validator "How Do I" videos on MSDN VB.NET and C# Comparison Good Coding Practices VBForums Reputation Saver String Enum Super Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  6. #6

    Thread Starter
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,612

    Re: Enum to represent String constants

    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:
    1. Public Shared Sub BindObjectToEnum(ByRef TargetControl As Object, ByVal SourceEnum As System.Type)
    2.     Dim selection = From item In [Enum].GetValues(SourceEnum) _
    3.                     Select New With {.Text = EnumDescription([Enum].ToObject(SourceEnum, item)), _
    4.                                      .Value = CInt(item)}
    5.     With TargetControl
    6.         .DisplayMember = "Text"
    7.         .ValueMember = "Value"
    8.         .DataSource = selection.ToList
    9.     End With
    10. End Sub

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


    Pradeep
    Last edited by Pradeep1210; Apr 15th, 2009 at 09:09 AM. Reason: Added sample usage.
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." Charles F. Kettering

    Read articles on My Blog 101 LINQ Samples JSON Validator XML Schema Validator "How Do I" videos on MSDN VB.NET and C# Comparison Good Coding Practices VBForums Reputation Saver String Enum Super Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  7. #7
    New Member
    Join Date
    Dec 2017
    Posts
    1

    Re: Enum to represent String constants

    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

  8. #8
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    102,920

    Re: Enum to represent String constants

    Quote Originally Posted by Tms72 View Post
    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:
    1. Dim selection = From item In [Enum].GetValues(SourceEnum)
    2.                 Let description = EnumDescription([Enum].ToObject(SourceEnum, item))
    3.                 Where description.Contains(someText)
    4.                 Select New With {.Text = description,
    5.                                  .Value = CInt(item)}

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width