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

Enumerations and Adding them to Structures

, 31 Dec 2008 CPOL
Rate this:
Please Sign up or sign in to vote.
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:

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:

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:

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:

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:

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:

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)

Share

About the Author

logicchild
Other Pref. Trust
United States United States
I started electronics training at age 33. I began studying microprocessor technology in an RF communications oriented program. I am 43 years old now. I have studied C code, opcode (mainly x86 and AT+T) for around 3 years in order to learn how to recognize viral code and the use of procedural languages. I am currently learning C# and the other virtual runtime system languages. I guess I started with the egg rather than the chicken. My past work would indicate that my primary strength is in applied mathematics.

Comments and Discussions

 
GeneralThoughts PinmemberPIEBALDconsult31-Dec-08 17:20 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.141022.1 | Last Updated 31 Dec 2008
Article Copyright 2008 by logicchild
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid