Click here to Skip to main content
Click here to Skip to main content

String Enumerations in VB.NET

By , 9 Nov 2012
 

Introduction

You have a program that needs to parse commands and then based on the result do something?

String enumeration in VB.NET would be the ideal answer, but enumerations in .NET are limited to numbers.

After a lot of web searching for a quick few lines of code, I put this code together to help others as many sites show more complex usage of enumerations as set examples.

The only rule in your program's command strings is keep the string simple without spaces, when you put them into your enumeration.

This little code snippet will then make parsing your command strings simple.

Using the code

Using the code will just require a new VB.NET Windows Forms project with a Textbox (Textbox1) , Label (Label1), and Button (Button1).

All your program command strings are put in the enumeration "ProgramCommands". Running the example will just need you to enter in the input box the exact string as found in your Enum. The label will show if your command was parsed OK.

Note the most important line in the code uses the [Enum].Isdefined function which checks if your string is in the Enum which returns true or false. Then we can parse the test string to see if a match is found. The matching string can then be used in the "Select Case" to perform actions on the command.

'Simple Commands via string enumeration by David. Rathbone.
Public Class Form1

'Enumeration of your programs commands note all in upper case
Private Enum ProgramCommands
    RUN_MOTOR
    STOP_MOTOR
    MOVE_ARM
    FIRE_GUN
End Enum

'Test button to input a command from a textbox
Private Sub Button1_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Button1.Click

    'Get Command From your programs input 
    Dim sCommandToTest As String = TextBox1.Text.ToUpper 'Keep string to upper case

    'First is the command to check in your program commands Enumeration? (True=Yes False= no)
    If CBool(CType([Enum].IsDefined(GetType(ProgramCommands), sCommandToTest), ProgramCommands)) Then

        'Command IS in Enumeration ~ now look though all the commands and get the one selected
        Dim testcase As ProgramCommands = _
               CType([Enum].Parse(GetType(ProgramCommands), sCommandToTest, True), ProgramCommands)

        'Just go through each case to add your commands action
        Select Case testcase
            Case ProgramCommands.RUN_MOTOR
                Label1.Text = "Run motor action stuff here"
            Case ProgramCommands.STOP_MOTOR
                Label1.Text = "Stop motor action Stuff here"
            Case ProgramCommands.MOVE_ARM
                Label1.Text = "Move arm action stuff here"
            Case ProgramCommands.FIRE_GUN
                Label1.Text = "Fire gun action stuff here"
            Case Else
                Label1.Text = "Should never get here!"
        End Select
    Else

        'Command Not in Enumeration
        Label1.Text = "False :- No such command"
    End If
End Sub
End Class

Points of Interest

For further details on string enumerations, please see http://msdn.microsoft.com/en-us/library/essfb559(v=vs.90).aspx, which will outline more details. In fact the MSN example gave me the idea that a more simple answer was needed!

History

First version: 13/08/2012.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

My Bones
Software Developer (Senior) Center Software and Electronics Ltd
United Kingdom United Kingdom
Member
David Rathbone is an electronics and software design engineer and has been in commercial hardware and software development for over 30 years. He has designed a number of products that are now used everyday all over the world.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
SuggestionCan simplify with [Enum].TryParsememberMatt T Heffron9 Nov '12 - 11:16 
Your:
    'Get Command From your programs input 
    Dim sCommandToTest As String = TextBox1.Text.ToUpper 'Keep string to upper case

    'First is the command to check in your program commands Enumeration? (True=Yes False= no)
    If CBool(CType([Enum].IsDefined(GetType(ProgramCommands), sCommandToTest), ProgramCommands)) Then
        'Command IS in Enumeration ~ now look though all the commands and get the one selected
        Dim testcase As ProgramCommands = _
               CType([Enum].Parse(GetType(ProgramCommands), sCommandToTest, True), ProgramCommands)
 
can be simplified to:
    'Get Command From your programs input 
    Dim sCommandToTest As String = TextBox1.Text
 
    Dim testcase As ProgramCommands 
    If [Enum].TryParse(sCommandToTest, True, testcase) Then
I've used the overload and option that is case-insensitive to avoid the need for the explicit .ToUpper and the requirement that the actual enumeration strings be defined as all UPPERCASE.
 
As the documentation for Enum.TryParse[^] indicates, the only reason for using IsDefined first would be to deal with cases where a numeric string may be provided instead of the enumeration string and it would be possible to get a numerc value that was NOT one of the defined enumeration values.
GeneralRe: Can simplify with [Enum].TryParse [modified]memberMy Bones10 Nov '12 - 0:10 
I like simple many thanks for your input....
However when I use the "String" Enum it is for calling Microcontroller functions which have the same Enum in its C header. My example is only an outline in VB.net only.
 
I use high level "GUI.net" string commands via TCP,UDP or Serial to send a simple Enum command number. The string Enum masks its real command numeric value. As long as you maintain the C header Enum and the VB.Net Enum, adding new commands requires no understanding of its numeric value, just its sudo string name.
 
You could just use "define" but Enum's allow you to just insert a new name.
 
Care in the Microsoft.net code should be taken if the Class holding the Enum has not yet been called or defined during the run time, So commands like isNothing(Object), isDefined(Type) are all get out of jail call's for poor .net functions offered by Microsoft. Ideally the .Net language should not through an exception at run time, but fail at design time forcing the user to see that the object or type may not yet be defined regardless of Class location.
 
Note in the VB.net example the Enum is in the same FORM class. In the real world the Enum would be in its own class, e.g. Controller_Settings_Header which would hold all the Enum's and default values used for your Microcontroller. in C# its can be the same header you use for your C Microcontroller code. In VB.net keeping this class simple just needs a few changes from its C header. So again watch out for your .net code needing isDefined first at run time.
 

Regards
David Rathbone Smile | :)

modified 10 Nov '12 - 6:32.

QuestionWhy bother with the enum at all?memberJohn Brett14 Aug '12 - 2:28 
For the use case you're giving, you might as well just switch directly on the string and be done with it.
 
John
AnswerRe: Why bother with the enum at all?memberMy Bones14 Aug '12 - 2:44 
Visual basic/C# and other dot.net code is object oriented.
 
You can pass the Enum to all classes that are using / parsing the String within Enum.
 
Passing Strings can be done, but what happens when you add new commands. Update versions etc.
 
Consider:-
Private mycommand as New EnumString
Or an Array:-
Private mycommand() as New EnumString
 
The array could be used to pass the same commands to diffrent controllers etc. Smile | :)
GeneralRe: Why bother with the enum at all?memberJohn Brett14 Aug '12 - 4:29 
Strings are objects too Smile | :)
 
However, my point was that your example was too simple to demonstrate the advantages you're proposing for your solution.
You have a large degree of complexity converting the string to an enum, and then an equally complex piece of logic to switch on the enum only to achieve nothing more than the switch on string solution.
 
There are plenty of cases where you would want to abstract the interface (e.g. the text from a TextBox) from the action, and an enum might be a useful intermediate. Then again, it might not (a map of string to Action<> might be a better architecture for example).
 
If you want to showcase your solution, you need a use-case where it is an improvement over the simpler option.
 
John
GeneralRe: Why bother with the enum at all?memberMy Bones14 Aug '12 - 9:28 
Its a code fragment to help others build into a more complex program.
I myself use Enum's and Structures in a base class within a Libary so only that base class needs changing not the whole program.
 
I'm not show casing just showing how simple/usefull the Enum to string funtion can be.
Big Grin | :-D
GeneralRe: Why bother with the enum at all?memberMike Tuersley12 Nov '12 - 7:26 
I would have to agree with John. How would you use this in something more complex? Enums only work if the values are known therefore you would never release something where the input could be arbitrary. You know the enums so you're going to populate a dropdown list, radio buttons, checkboxes, etc.
 
Having said that, I am not dismissing this Smile | :) I'd just like to see something that would compell me to look at this closer.
_____________________________
Mike Tuersley

GeneralRe: Why bother with the enum at all?memberMy Bones12 Nov '12 - 7:46 
Look at my reply to Matt
 
You Use Enums in C header as well as your dot net code
This means your strings only read well in both C code and .Net but mask its number
its nothing to do with further functions you use in .net
 
Regards
 
Dave

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 9 Nov 2012
Article Copyright 2012 by My Bones
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid