Jump to content

C# - Enums

- - - - -

  • Please log in to reply
7 replies to this topic

#1
CommittedC0der

CommittedC0der

    Speaks fluent binary

  • Members
  • PipPipPipPipPipPipPipPip
  • 1,565 posts
Hello! Today we'll be covering enums which is for short for enumerator. This tutorial is marked as intermediate because it can be confusing and most likely wont be used by the beginning programer.


What is an Enum?
MSDN: The enum keyword is used to declare an enumeration, a distinct type consisting of a set of named constants called the enumerator list.

English: An enum is a place to store and keep track of constants with integers values. These enums not only keep code more readable but can also make it easier to work with.

When to use Enums?
Enums should be used when you have multiple constants that pertain to each other enough to be placed in a single group. For example, let’s say you have these constants with integer values:
const int North = 0;
const int East  = 1;
const int South = 2;
const int West  = 3;
The example North, East, South and West, is a good example because they all relate to each other enough to fit in one enum named "Direction", as we'll go over.

Declaring Enums.
The first thing to do is declare our enum followed by its name.
enum Direction
{
 
};
I name our enum "Direction" because this name pertains to its contents, and makes it generally easier to remember.

Now we can add our constants inside both braces, making sure to add a comma before adding a new constant.
enum Direction
{
  North = 0, [COLOR=#008000]//Notice the keyword "const" and "int" are not needed.[/COLOR]
  East  = 1,  [COLOR=#008000]//Everything inside and enum is automatically declared as constant.[/COLOR]
  South = 2,
  West  = 3
};
I mentioned the keyword "int" is also not needed, this is because all enum constants are type int by default, but they can be changed by assigning the integer type to the end of the enum name.
enum Direction : short
{
  North = -32767,
  East  = 32767,
  South = 2,
  West  = 3
};
As you can see I created "short" constants, but you may also create byte, sbyte, ushort, int, uint, long, and ulong constant types.

By default if the constants are un assigned they will automatically take the value of the the last constant in the enum plus one, starting from 0.
enum Direction
{
  North, [COLOR=#008000]// North = 0[/COLOR][COLOR=#008000] automatically[/COLOR]
  East, [COLOR=#008000]// East = 1 automatically[/COLOR]
  South = 4, [COLOR=#008000]// This will affects West's value.[/COLOR]
  West [COLOR=#008000]// West now = 5[/COLOR]
};


Reference.
There is something else we can do with enums though, and that is you can create a special instance that can equal any of our constants values. The most common use for this is in a switch or, if else statement. Below is an example of how these statements work with our enum instance.
Direction dir = Direction.North;
switch (dir)
{
    case Direction.North: [COLOR=#008000]//Our dir value is North so we'll see this.[/COLOR]
        MessageBox.Show("You picked North.");
        break;
}
if(dir == Direction.North) [COLOR=#008000]//As we know, our dir value is North so we'll also see this.[/COLOR]
  MessageBox.Show("You picked North.");

If that was easy enough to understand then hopefully you'll understand using user input to declare the value of "dir".

string input = textBox1.Text; [COLOR=#008000]// Im using a textBox to get input, you may use whatever you like.[/COLOR]
Direction dir = (Direction)Convert.ToInt32(input);
We receive the input from the user and assign a new Direction. To understand how "dir" gets its value we'll assume the constants are defined like so:
 North = 0, 
  East  = 1,  
  South = 2,
  West  = 3
(Its important to note that the user types a number as input, not a word.)
Now, "dir"s value is based off the user's input, we'll assume the user inputs a number between 0 and 3. When we receive the input we assign "dir"s value to the input. To better understand let’s say the input is “0”, we have a constant equal to "0" in our enum, its name is "North". So "dir"s value would become North, likewise, if we get "1" as the input "dir"s value would become East.
Think of it like this; There are numbers in the enum that have names assigned to them, if we get the input "2" our "dir" value is 2. Now the name correlating with the value 2, is? South!

I hope that was understandable. :)
Now we can easily compare values through our enum instance with the true enum, like so.
Switch statement:
string input = textBox1.Text;
Direction dir = (Direction)Convert.ToInt32(input);
switch (dir)
{
    case Direction.North: [COLOR=#008000]//If the input is "0" You'll see this.[/COLOR]
        MessageBox.Show("You picked North.");
        break;
    case Direction.East: [COLOR=#008000] //If the input is "1" You'll see this.[/COLOR]
        MessageBox.Show("You picked East.");
        break;
    case Direction.South:[COLOR=#008000] //And so on...[/COLOR]
        MessageBox.Show("You picked South.");
        break;
    case Direction.West:
        MessageBox.Show("You picked West.");
        break;              
}

Again, this time using an If Else statement, which is slightly easier understand:
string input = textBox1.Text;
Direction dir = (Direction)Convert.ToInt32(input);
if(dir == Direction.North)     [COLOR=#008000]//If the input is "0" You'll see this.[/COLOR]
  MessageBox.Show("You picked North.");
else if(dir == Direction.East) [COLOR=#008000]//If the input is "1" You'll see this.[/COLOR]
  MessageBox.Show("You picked East.");
else if(dir == Direction.South)
  MessageBox.Show("You picked South.");
else if(dir == Direction.West)
  MessageBox.Show("You picked West.");


Before we leave off I should also mention that you can refence the constants direct value by casting it.
MessageBox.Show(Convert.ToString((int)Direction.North));
[COLOR=#008000]//Or a more readable version...[/COLOR]
int x = (int)Direction.North;
MessageBox.Show(x.ToString()); [COLOR=#008000]// Will show the value of North, which is "0".[/COLOR]
As you can see, you dont always have to refer to your constant through an instance, it can still be used like a normal constant.


The End.
Output:
Attached File  enums.png   27.06K   53 downloads
Although it may not be majorly apparent in this small tutorial, I hope you see how this method of keeping constants contained can really help clean your code, make it easier to work with and add in a few things you couldnt do before.

If you managed to not get confused throughout this tutorial, and where able to understand how to use enums to your advantage, great! If there are any parts you are unable to understand just post, and I'll try my best to explain them.

As always, questions, comments, and +rep welcome! If you will, please use the “Rate this Thread” button at the top of this post.
Thanks ~ Committed. :)

Edited by CommittedC0der, 20 August 2011 - 07:37 PM.

A man can be defined by what he does when no one is looking.
Science is only an educated theory, which we cannot disprove.

#2
RhetoricalRuvim

RhetoricalRuvim

    JavaScript Programmer

  • Members
  • PipPipPipPipPipPipPipPip
  • 1,254 posts
  • Location:C:\Countries\US

Quote

const int North = 0;

const int East  = 1;

const int South = 2;

const int West  = 3;

Constants are defined like that? I though they were defined like this:
#define North 0 

#define ...and so on...  


And the other thing, you kind of lost me at the user input part; how does C# know that user input "north" means 0? Or does the user have to type the number 0?


But overall, nice tutorial.

#3
CommittedC0der

CommittedC0der

    Speaks fluent binary

  • Members
  • PipPipPipPipPipPipPipPip
  • 1,565 posts

Quote

Constants are defined like that? I though they were defined like this:
#define North 0  
#define ...and so on...
I think your thinking of C++? In C# we use the "const" keyword.

Quote

And the other thing, you kind of lost me at the user input part; how does C# know that user input "north" means 0? Or does the user have to type the number 0?
Ehh I know, I was trying to be as clear as I could but its difficult to explain. When the user inputs 0 the "dir" value becomes North because North = 0. I'll try and edit that part to make it clearer, once i get time.

Thanks for the feed back ~ Committed. :)
A man can be defined by what he does when no one is looking.
Science is only an educated theory, which we cannot disprove.

#4
CommittedC0der

CommittedC0der

    Speaks fluent binary

  • Members
  • PipPipPipPipPipPipPipPip
  • 1,565 posts
I tried rewriting it, tell me what you think.
~ Committed.
A man can be defined by what he does when no one is looking.
Science is only an educated theory, which we cannot disprove.

#5
RhetoricalRuvim

RhetoricalRuvim

    JavaScript Programmer

  • Members
  • PipPipPipPipPipPipPipPip
  • 1,254 posts
  • Location:C:\Countries\US

Quote

Think of it like this; There are numbers in the enum that have names assigned to them, if we get the input "2" our "dir" value is 2. Now the name correlating with the value 2 is? West!

But you said 2 is South.

Though it is more understandable now, I would say. So the user types a number, and not a word; that makes more sense.

#6
CommittedC0der

CommittedC0der

    Speaks fluent binary

  • Members
  • PipPipPipPipPipPipPipPip
  • 1,565 posts
West was a typo and a rather large one at that. I also added your comment about the input being a number, not a word.

+rep for your help, and all the great tuts you've made this far.
Thanks ~ Committed. :)
A man can be defined by what he does when no one is looking.
Science is only an educated theory, which we cannot disprove.

#7
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,118 posts
  • Location:Vancouver, Eh! Cleverness: 200

CommittedC0der said:

West was a typo and a rather large one at that. I also added your comment about the input being a number, not a word.

+rep for your help, and all the great tuts you've made this far.
Thanks ~ Committed. :)

Very nice, I enjoy how you did it in spirit of those old text games where you have to choose a direction. For the life of me I cannot remember the game's name.
Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.

#8
CommittedC0der

CommittedC0der

    Speaks fluent binary

  • Members
  • PipPipPipPipPipPipPipPip
  • 1,565 posts
Thank you. :)
~ Committed.
A man can be defined by what he does when no one is looking.
Science is only an educated theory, which we cannot disprove.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users