Home > Articles

Introducing C#

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book


Most C/C++ programmers are probably familiar with enumerators. Enumerators are often used when constant values must be combined with text. In the case of small lists, this works well and can make C# programs easier to read.

In the next example, you learn how enumerators can be implemented. The target of the example is to see how the days of a week can be processed:

using System;

class  Demo
    public enum Days: byte
        monday, tuesday, wednesday, thursday,
        friday, saturday, sunday

    public static void Main()
        Days MyDay;
        Array DayArray = Enum.GetValues(typeof(Demo.Days));
        foreach (Days Day in DayArray)
            Console.WriteLine(Day + " = "
                + Day.ToString("d"));

Inside the class, we define an enumerator that's derived from byte. Inside the Main function, we define a variable that has the same data type, and we define an array that contains the values of the enumerator. For that purpose, we use the GetValues method. Finally, we process all values one after the other and display a string on screen. The output looks like this:

[hs@duron mono]$ mono ex.exe
monday = 0
tuesday = 1
wednesday = 2
thursday = 3
friday = 4
saturday = 5
sunday = 6

Mono displays the names of the days plus the various numbers. All together we have stored seven values.

  • + Share This
  • 🔖 Save To Your Account