Enumerations in VB.NET
page 1 of 1
Published: 02 Dec 2003
Unedited - Community Contributed
Abstract
A common mistake made by most programmers is the use of hard coded literal strings or numeric values. Some wise programmers make use of public constants but this too becomes unmanageable when they are greater in numbers. Also the naming conventions for the constants are weird and it is onto the sole discretion of the programmer. Enumerations provide an elegant solution to this problem, and their use within VB.NET is covered here.
by Pani Baruri & Abhijit Mandrekar
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 16601/ 16

Enumeration

It has the following advantages:

  • It eliminates the hard coding of literal values.
  • When used the code is more readable and easy to maintain.
  • The constants within the enumeration receive values automatically unless specified by the user
  • Naming the constants within enumeration is easy and they are distinguishable by the containing enumerator even when the same name is defined in other enumerator.

 

The simple example of Enumeration is illustrated as below.

 

The customer is filling out restaurant survey. Upon completion of the survey total score is calculated and prompts the restaurant to take some action based on it. The responses to the questionnaire are categorized as Excellent, Good, Average, Fair, and Poor. Define the enumerator as:

 

Enum EnumResponse

        Excellent = 2

        Good = 1

        Average = 0

        Fair = -1

        Poor = -2

End Enum

 

Enum EnumResult

        Excellent = 10

        Good = 5

        Average = 0

        Fair = -5

        Poor = -10

End Enum 

The UI contains radiobuttonlist control to get an answer to each question. The following function will return the score.

 

Function GetScore(ByVal ctlRadioBtn As   Web.UI.WebControls.RadioButtonList) As Int16

        Select Case ctlRadioBtn.Selected.Value

            Case EnumResponse.Excellent

                Score = 2

            Case EnumResponse.Good

                Score = 1

            Case EnumResponse.Average

                Score = 0

            Case EnumResponse.Fair

                Score = -1

            Case EnumResponse.Poor

                Score = -2

        End Select

End Function

 

 

 

One more common problem with the programmers is comparison of strings. The problem is in determination of the case of the string, whether it is lower case or upper case or mixed case. The program does not work for the first time then debugging kicks in and correction is made in the form of hard coding the literal value to appropriate case. Why not use enumeration here?

 

More explanation with the restaurant survey example is as below. The question is “Would you dine here again?”. The UI presents three options Yes, No and Maybe using DropDownList box control and these options are coded in HTML.

 

One may write the code to compare the selection as

 

        If ctlDropDownBox.Selected.Text = "Yes" Then

            '…

        ElseIf ctlDropDownBox.Selected.Text = "No" Then

            '….

        ElseIf ctlDropDownBox.Selected.Text = "Maybe" Then

            '…

     End If

 

Imagine the above dropdownlist box is now getting filled from database with values as YES, NO, MAYBE. The above code will surely fail to do its intended job. Instead if you would have written the code using enumeration as below then no revisit to code is required or visit to enumerator definition or change to its contents are more efficient than finding and replacing literal strings.

 

Enum EnumPrompts

        YES

        NO

        MAYBE

End Enum

     selectedEntry = UCase(ctlDropDownBox.Selected.Text)

        If selectedEntry = GetName(EnumPrompts.YES) Then

         '…

        ElseIf selectedEntry = GetName(EnumPrompts.NO) Then

        '….

        ElseIf selectedEntry = GetName(EnumPrompts.MAYBE) Then

         '…

        End If

 Final Note: As you have seen the enumerations avoid common mistakes made by the programmer, use it wisely where needed. Though it may not 100 percent eliminate literal strings but 95 percent will be cleaned out for certain.

 



User Comments

Title: not bad   
Name: anshu
Date: 2011-01-07 12:28:47 PM
Comment:
i understand these code..and satisfied
Title: Not really understand   
Name: Brad
Date: 2010-09-05 12:28:11 PM
Comment:
I don't really understand the use or enumerations. It's only used to limit the possibility of value right? So why we should build a new type of variable for that?
Title: Excellent   
Name: Evil Dr
Date: 2010-04-09 6:58:31 AM
Comment:
Excellent article. I was not aware you could declare Enums without an underlying type.
Title: please tell me the answer for this   
Name: jai
Date: 2010-03-19 2:57:04 AM
Comment:
5. In Visual Basic, if an enumeration called 'j' with the values 'r = 4', 'q = 3' and 't = 1' is declared, what is the output of these statements?
dim x as j = j.r
dim y as integer = j.t msgbox(x & " " & y)
Title: Enumerations in VB.NET   
Name: Richard
Date: 2008-08-01 3:44:06 PM
Comment:
Good example of using enumenrations. Simple and direct.
Title: Literals - a rebuttal   
Name: Neil Taylor
Date: 2008-04-17 4:15:27 PM
Comment:
I came here looking for the best way to define a literal and isolate it from the item it alludes to and this looks like a perfect answer to that; for which I thank you.

That said; I would have to say that I disagree strongly with the assertion that the use of hard coded literals is presumptively a bad thing. On the contrary I believe that in a significant majority of cases the changing of a literal to a defined constant has no value whatsoever and in many cases is actually counter productive.

Changing ...
If ddlChoice.selectedIndex = 1
to
If ddlChoice.selectedIndex = enumReports.Dealer

... obviously has some value however changing ...

set tHeading = "Monthly Dealer Report"
to
set tHeading = enumHeadings.dealer
... is a colossal waste of time, unnecessarily increases the amount of code to be viewed, creates an additional and time wasting need to jump back and forth to see what's actually being set, and creates the possibility for horrible and time wasting misunderstandings.

This is a great answer to how to do something that's often useful and valid. I absolutely disagree that it's something that should ALWAYS be done.
Title: Enum   
Name: King Wilder
Date: 2006-08-06 2:27:18 PM
Comment:
In your enum example, how do you get the enum into the function GetName()?

More specifically, how can I declare a global Enum to be used in any procedure as an argument in any class of the project?

I get an error saying that I "cannot expose the type outside the project through a class".

Example:

Public Enum icPriority
Low
Medium
High
End Enum

Public Class else in the project:

Class Stuff
Public Sub MakeSomething(ByVal p as icPriority) ' This returns an error

End Sub
End Class
Title: Enum   
Name: C.Ashish
Date: 2006-05-09 12:09:02 AM
Comment:
Very good article about Enum devloper can understand how to avoid hardcoding of litral.
Title: Enum   
Name: shanthi
Date: 2006-03-18 10:58:01 PM
Comment:
The article about enum is worth reading. If this site covers all the topics of vb.net it will be useful for the beginners.

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-16 3:22:15 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search