C# Enums and HashSets (.Net)

The C# equivalents of Pascal's enumerated type and set are enum and HashSet, respectively. This example demonstrates the Remove method of a HashSet. Once you have declared a HashSet you can use IntelliSense to see other methods such as Add, IntersectWith and IsSubsetOf. RemObjects C# has useful pred and succ methods for use with enums. The code required to emulate these is convoluted and responses to a stackoverflow question state that Microsoft (the originators of the C# language) expected you to use alternative data structures to achieve this functionality.

A copy of the output follows the code of the demonstration.

using System;
using System.Collections.Generic;

namespace enums_and_sets
{
  static class Program
  {
    enum planets {Mercury, Venus, Earth, Mars, Jupiter,
                  Saturn, Uranus, Neptune, Pluto};

    public static void Main(string[] args)
    {
      HashSet<planets> gas_giant = new HashSet<planets>(){
                             planets.Jupiter, planets.Saturn, 
                             planets.Uranus, planets.Neptune};
    	
      var MercuryPos = (int)planets.Mercury;
      var PlutoPos = (int)planets.Pluto;  	
      Console.WriteLine("Position of Mercury in enum: " + MercuryPos);
     
      foreach (var p in System.Enum.GetValues(typeof(planets))) 
      {
      	if ((int)p == MercuryPos + 1) 
          Console.WriteLine("Successor of Mercury in enum: " + p);
        if ((int)p == PlutoPos - 1) 
          Console.WriteLine("Predecessor of Pluto in enum: " + p);      	
      }
    
      Console.Write("All of the gas giants: ");
      foreach (var p in gas_giant)
      {
        Console.Write(p);
        Console.Write(" ");
      }
      Console.Write("\nGas giants excluding Neptune: ");
      gas_giant.Remove(planets.Neptune);
      foreach (var p in gas_giant)
      {
        Console.Write(p);
        Console.Write(" ");
      }
      Console.WriteLine(); 
      Console.ReadLine();
    }
  }
}

Output:
Position of Mercury in enum: 0
Successor of Mercury in enum: Venus
Predecessor of Pluto in enum: Neptune
All of the gas giants: Jupiter Saturn Uranus Neptune
Gas giants excluding Neptune: Jupiter Saturn Uranus

Programming - a skill for life!

C# Demonstrations of I/O, arrays, methods, classes, loops, enums, pointers, file handling, Firebird databases, LINQ and drawing on a form