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

.NET Enumerated Types Explained

By , 3 Jul 2010
 

Introduction

The purpose of this article is to provide an introduction to .NET enumerated types.

Background

Code readability is a big factor when considering the quality of source code. The easier code is to understand, the easier it is to maintain. Have you ever found yourself using numbers to represent a range of variable values? For example:

Dim CalculationOperation As Integer = 0
CalculationOperation = _ GetOperation ()
Select Case CalculationOperation
    Case 1 ’ Addition
        _PerformAddition()
    Case 2 ‘ Subtraction
        _PerformSubtraction()
    Case 3 ‘ Multiplication
        _PerformMultiplication()
End Select

This requires you as well as any other developers that might touch your code to remember all of the possible numeric values that represents colors. This can be a maintenance nightmare! To solve this problem, VB.NET has enumerated types.

Reasons to Use Enumerated Types

Readability

From Wikipedia:

"In computer programming, an enumerated type (also called enumeration or enum) is a data type consisting of a set of named values called elements, members or enumerators of the type. The enumerator names are usually identifiers that behave as constants in the language."

Enumerated types allow you to give an English description to a range of integer values. Perhaps an example will explain this.

Public Type CalculatorOperations
    Addition       = 1
    Subtraction    = 2
    Multiplication = 3
End Type

Dim Operation As CalculatorOperations
Operation = _ GetOperation ()
Select Case Operation
    Case CalculatorOperations.Addition
        _PerformAddition()
    Case CalculatorOperations.Subtraction
       _PerformSubtraction()
    Case CalculatorOperations.Multiplication
       _PerformMultiplication()
End Select

This routine is easier to read.

When coding a routine, be sure to consider numeric literals that represent a value other than the number itself as a possible reason to create an enumerated type.

Enums as Routine Parameters

Enumerated types are great as routine parameters. Consider the following example.

Bad Example

Dim ApplicationState as Integer = 5 ‘lets say five stands for Fatal Crash!
Sub _SetApplicationState(ByVal State As Integer)

Good Example

Dim ApplicationState As AppState = AppState.FatalCrash
Sub _SetApplicationState(ByVal State As AppState)

If you are using Visual Studio, then you no doubt have noticed the benefit of using enumerated types as function parameters. While you are writing the code to call the routine, intellisense will show you all available members of the enumerated type.

Compiler Type Checking

Using enumerated types also provides type checking by the compiler. Consider the following block of code:

‘Valid color values are 09
Dim CurrentColor As Integer
CurrentColor = 12 ‘invalid color

This is impossible with enumerated types. Enumerated types can make powerful return values. Consider the following code:

Dim LoginResult As Boolean = false
LoginResult = _AttemptLogin()
If LoginResult = True Then
    _Authenticateuser()
End If
If LoginResult = False Then
     _InitiateLogin()
End If

As you can see, true and false allow for two conditions:

Dim LoginResult As AuthResult 
LoginResult = _AttemptLogin()
If LoginResult = AuthResult.Authenticated Then
    _Authenticateuser()
End If

If LoginResult = AuthResult.Failed Then
    _InitiateLogin()
End If

If LoginResult = AuthResult.Suspended Then
    _AlertSuspended()
End If

If LoginResult = AuthResult.AuthenticatedChangePassword Then
    _InitiatePasswordChange()
    _AuthenticateUser()
End If

Do you see the possibilities?

Define the First and Last Entry as Loop Limits

You may find yourself in a situation where you need to iterate through each member of your enumerated type. One suggested practice is to reserve the first and last element as loop limits.

Public Type RGBValue
 RGB_FirstValue = 0
 RGB_Red = 0
 RGB_Green = 1
 RGB_Blue = 2
 RGB_LastValue = 2
End Type

Dim RGBVal As RGBValue
For RGBVal = RGBValue.RGB_FirstValue To RGBValue.RGB_LastValue
 ‘process here
Next

Conclusion

Well, I hope I’ve illustrated some of the benefits of using enumerated types. All of your feedback is welcome.

Thanks,
Bryan James
MCP, MCAD, MCSD.NET
http://www.bytepushers.com
http://www.twitter.com/budbjames

History

Version 1 07/3/2010

License

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

About the Author

bjames02
Software Developer bytepushers.com
United States United States
Member
I'm a 28 year old software engineer from Tennessee. I've been programming since I was 13 years old. I'm fortunate enough to be able to do what I love for a living.
 
VB.NET, ASP.NET, C#, assembly, HTML, JavaScript, AJAX
 
I'm MCP, MCAD, MCSD.NET certified.
 
follow me on twitter
 
http://www.twitter.com/budbjames

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   
GeneralNice explainationmemberBigdeak17 Aug '10 - 3:31 
It is really useful for newbies or for some who didn't know this.
 
Well, instead of using if in this case, a Select Case should be used in my oppinion:
 
Dim LoginResult As AuthResult 
LoginResult = _AttemptLogin()
Select Case LoginResult
    Case AuthResult.Authenticated
       _Authenticateuser()
    Case AuthResult.Failed
       _InitiateLogin()
    Case AuthResult.Suspended
       _AlertSuspended()
    Case AuthResult.AuthenticatedChangePassword
       _InitiatePasswordChange()
       _AuthenticateUser()
End Select
 
Hope you know what code i mean Smile | :)
GeneralRe: Nice explainationmemberbuddy.james23 Sep '10 - 21:29 
Noted. I will update to use a SELECT CASE
 
And of course I know what it is Smile | :)
 
Thanks for readying.
GeneralPretty good explanation for newbiesmemberShane Story7 Jul '10 - 9:10 
Bryan,
 
This is a pretty good explanation for newbies.
I would add/change the following:
 
I'm not sure the limiting things are such a good idea anymore. Intellisense can tell the coder if it is valid or not. To check one can also do the enum.IsDefined() method to see if the value is valid.
 
I have found there are also times when you want all of the actual enumeration names. Take for example a list of colors to choose from--by known color name. They already exist.
 
 
  For Each s As String In [Enum].GetNames(GetType(System.Drawing.KnownColor))
     'for this example, just writes known color names to debug window
      Debug.WriteLine(s)
      'this could be a listbox where you add the names of colors
      'so the user sees the names and you remember the value
  Next
 
As for editing HTML, I really love Notepad++.
http://notepad-plus-plus.org/[^]
 
It runs circles around Notepad.
 
It would probably take the time, in this article to mention using enum.[whatever property].
I have mentioned two of the properties.
 
Well, keep the articles rolling. You will get better at the formatting and I have definitely seen worse on here. This one is pretty basic, but some people are just starting and need basic beginner's stuff.
Wish I'd had the internet when I was starting programming 29 years ago.
 
Be blessed!
Shane
Jesus loves you! John 3:16 · Rom 3:23 · Rom 6:23 · Rom 10:9

GeneralRe: Pretty good explanation for newbiesmemberbjames027 Jul '10 - 18:33 
Shane,
 
Thanks for reading and the suggestions. I'll try to add some information or links to the Enum type's shared methods
 
I'll add your example, however, I think I'll still leave the other implementations for diversity.
 
Thanks.
GeneralNot an articlememberJohn Simmons / outlaw programmer3 Jul '10 - 2:01 
This should be deleted and re-posted as a tip/trick.
.45 ACP - because shooting twice is just silly
-----
"Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
-----
"The staggering layers of obscenity in your statement make it a work of art on so many levels." - J. Jystad, 2001

GeneralNeeds formattingmvpRichard MacCutchan2 Jul '10 - 23:04 
Your code snippets would show up better if formatted in accordance with CodeProject standards, i.e. surrounded with <pre></pre> tags. You also seems to have used a non standard font for the text portions of your article. Take a look at the article guidelines[^] for more information.
It's time for a new signature.

GeneralRe: Needs formattingmemberbjames023 Jul '10 - 0:09 
I can't seem to format the code.. any help?
GeneralRe: Needs formattingmvpRichard MacCutchan3 Jul '10 - 0:37 
bjames02 wrote:
I can't seem to format the code.. any help?

 
As I said in my previous message, and as stated in the article guidelines, just surround your code snippets with <pre></pre> tags.
 
For example if I enter the following lines:
<pre lang="vbnet">
Dim CalculationOperation As Integer = 0
CalculationOperation = _ GetOperation ()
</pre>
it will appear as
Dim CalculationOperation As Integer = 0
CalculationOperation = _ GetOperation ()
Nice and clear for others to read.
It's time for a new signature.

GeneralRe: Needs formattingmemberJohn Simmons / outlaw programmer3 Jul '10 - 2:00 
I reformatted it for you. Your formatting problems stem from using some sort of html editor when you wrote your article. Generally, this is a BAD idea because it puts a lot of useless crap in your text that isn't necessary here at CP. This site has it's own styles, and adding html tags should pretty much be limited to the following:
 
<H1> through <H4>
<p>
<b>
<i>
<code>
<pre>
<ul>
 
There is absolutely no reason to add styles or classes to your tags here. By using an editor that "converts" or "exports" to html, you introduce a lot of useless crap. It took me almost 30 minutes to clean it up.
.45 ACP - because shooting twice is just silly
-----
"Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
-----
"The staggering layers of obscenity in your statement make it a work of art on so many levels." - J. Jystad, 2001

GeneralRe: Needs formattingmemberbjames025 Jul '10 - 17:42 
I really appreciate the assistance.
 
I actually simply type my article up in MS word and then copy and paste. It does add a ton of junk and makees it extremely hard for me to format.
 
I will try with the tags that you've suggsted and notepad next time.
 
Thanks again.
GeneralRe: Needs formattingmemberSSDiver21126 Jul '10 - 18:15 
Take a look at this article. The download will be a big help to you when writing your article.
 
A Code Project Article Editor with Live Preview[^]
GeneralRe: Needs formattingmemberJohn Simmons / outlaw programmer7 Jul '10 - 11:31 
I use Visual Studio to edit my articles. The syntax highlighting supports HTML, so it's kind of a no-brainer.
.45 ACP - because shooting twice is just silly
-----
"Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
-----
"The staggering layers of obscenity in your statement make it a work of art on so many levels." - J. Jystad, 2001

GeneralRe: Needs formattingmemberbjames027 Jul '10 - 18:29 
Thanks for the input.
 
I like to use CrimsonEditor for HTML only stuff. It's a nice, free, light weight source editor.
 
No more MS Word for codeproject articles.

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

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130516.1 | Last Updated 3 Jul 2010
Article Copyright 2010 by bjames02
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid