Click here to Skip to main content
15,867,321 members
Articles / Programming Languages / C#
Article

Enumerations and Adding them to Structures

Rate me:
Please Sign up or sign in to vote.
1.67/5 (5 votes)
31 Dec 2008CPOL3 min read 22.1K   10   4
An article to help a beginner understand C# enumerations.

Introduction

This article is meant for the beginner. As such, it will describe enumerations and add them to structures. One important point should be made about enum types, and that is that while they appear to look much ordinary types in metadata, enum types abide by a strict set of rules as defined in the Common Type System (CTS). For example, defining methods or constructors on enum types is prohibited, as is implementing interfaces, and they can only have a single field to represent the value. Enumerations are therefore related symbols that have fixed values. This allows your code to avoid “magic numbers”.

So, what is an enumeration (a.k.a. enum)?

An enumeration is a special type that maps a set of names to numeric values. Using them is an alternative to embedding constants in your code, and provides a higher level of nominal type safety. As stated earlier, enumerations are related symbols that have fixed values. You can use enumerations to provide a list of choices for developers using your class. For example, the following enumeration contains a set of titles:

C#
using System;
enum Titles : int { Mr, Ms, Mrs, Dr };
class App {
 static void Main(string[] args) {
  Titles t = Titles.Dr;
  Console.WriteLine("{0}.", t);
       }
}

Output:

Dr.

Stated loosely, enumerations are basically types that have a special function in that they limit the values that the particular type in hand can contain. In this code snippet below, that variable can only have one of the four values stated in the braces: BusBoy, Waiter, Bartender, or Manager. These values are of type MyUserType, and by default, represent an integer value. These values are similar to an array in that they are zero-based: four of them would have the values 0, 1, 2, 3. Enumerations are similar to constants in that they allow you to avoid "magic numbers", as their values are fixed. By using enumerations, you can allow other developers to use them while having restricted their values. So, to create or declare a variable of type MyUserType:

C#
public enum MyUserType
{
     BusBoy,
     Waiter,
     Bartender,
     Manager        
}

Again, that variable can only have one of the four values stated in the braces: BusBoy, Waiter, Bartender, Manager. These values are of type MyUserType, and, by default, represent an integer value. These values are similar to an array in that they are zero-based: four of them would have the values 0, 1, 2, 3. So, we see that enumerations are similar to constants in that they allow you to avoid "magic numbers", as their values are fixed. By using enumerations, you can allow other developers to use them while having restricted their values. Below are two examples: one is based on the code snippet above, and the other is based on assigning BusBoy a value of 1:

C#
using System;
class Program 
   {
     public enum MyUserType {
           BusBoy,
           Waiter, 
           Bartender,
           Manager
     }
  static void Main(string[]  args)
   {
      switch(int.Parse(args[0]))
      {
         case (int)MyUserType.BusBoy:
         Console.Write("BusBoy");
         break;

         case (int)MyUserType.Waiter:
         Console.Write("Waiter");
         break;

         case (int)MyUserType.Bartender:
         Console.Write("Bartender");
         break;

         case (int)MyUserType.Manager:
         Console.Write("Manager");
         break;

 default:
          Console.Write("Default");
          break;
        }
   }
}

1.JPG

The second example assigns a 1 to BusBoy:

C#
using System;
class Program 
{
     public enum MyUserType {
           BusBoy = 1,
           Waiter, 
           Bartender,
           Manager
     }
    static void Main(string[]  args)
    {
      switch(int.Parse(args[0]))
      {
         case (int)MyUserType.BusBoy:
         Console.Write("BusBoy");
         break;

         case (int)MyUserType.Waiter:
         Console.Write("Waiter");
         break;

         case (int)MyUserType.Bartender:
         Console.Write("Bartender");
         break;

         case (int)MyUserType.Manager:
         Console.Write("Manager");
         break;

 default:
          Console.Write("Default");
          break;
      }
   }
}

Note that when we pass a value of 1, we get this output:

2.JPG

The following code creates a structure. It is important for the beginner to read the comments:

C#
using System;

struct Person
// create a new structure called Person
{
    // within the structure Person, define three public members
    public string firstName;
    public string lastName;
    public int age;

    // create a contructor that initializes all three member variables

    public Person(string _firstName, string _lastName, int _age)
    {
        firstName = _firstName;
        lastName = _lastName;
        age = _age;
    }

    // override the System.Object's ToString() method to display
    // the person's first and last name, with his age

    public override string  ToString()
    {
        return firstName + "  " + lastName + ", age " + age;
    }
}
class Program
{
    static void Main(string[] args)
    {
        Person p = new Person("Robert", "Allen", 43);
        Console.WriteLine(p);
    }
}

Output:

Robert Allen, age 43

Adding an enumeration to a structure

In this example, we declare a new enumeration in the Person structure. We name the enumeration Genders, and specify two possible values: Male and Female. The code below demonstrates this:

C#
using System;

struct Person
{
    public enum Genders : int { Male, Female };

    public string firstName;
    public string lastName;
    public int age;
    public Genders gender;
   
    public Person(string _firstName, string _lastName, 
                  int _age, Genders _gender)
    {
        firstName = _firstName;
        lastName = _lastName;
        age = _age;
        gender = _gender;
    }


    public override string  ToString()
    {
        return firstName + " " + lastName + " (" + 
                           gender + "), age " + age;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Person p = new Person("Robert", "Allen",  
                              43, Person.Genders.Male );
        Console.WriteLine(p);
    }
}

Output:

Robert Allen (Male), age 43

An enum is a special value type that lets you specify a group of name numeric constants, without embedding constants in your code.

License

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


Written By
Software Developer Monroe Community
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 1 Pin
Patric_J2-Jan-09 3:51
Patric_J2-Jan-09 3:51 
GeneralMy vote of 1 Pin
Dmitri Nеstеruk1-Jan-09 2:51
Dmitri Nеstеruk1-Jan-09 2:51 
GeneralMy vote of 1 Pin
Samer Aburabie31-Dec-08 23:43
Samer Aburabie31-Dec-08 23:43 
GeneralThoughts Pin
PIEBALDconsult31-Dec-08 17:20
mvePIEBALDconsult31-Dec-08 17:20 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.