Creating Dynamic Enums using C#

Further to my article about creating generic enums using C# ( and a response from Suthish Nair, the following code needs to be added to the GenericEnum base class to enable new members to be added dynamically.

I didn't think it was a good idea to allow for removal of members already added because this could upset instances which had already been created in the same session.

    private static int dynamicCount;

    public static int DynamicCount
        get { return dynamicCount; }

    public static void DynamicAdd(string name, U value)
        if (names.IndexOf(name) == -1)
            throw new InvalidOperationException(String.Format("'{0}' is already an element of {1}", name, typeof(T).Name));

Finally, here's some sample code to test the above:

class Test
   static void Main()

      Fractions f = Fractions.ByName("Sixth");
      Console.WriteLine(f); // Sixth      
      Fractions.DynamicAdd("Seventh", 1.0/7.0);
      Fractions.DynamicAdd("Eighth", 0.125);
      Console.WriteLine(f); // Sixth (unchanged)
      f = Fractions.ByName("Seventh");
      Console.WriteLine(f); // Seventh
      Console.WriteLine(f.Value.ToString("F4")); // 0.1429
      Console.WriteLine(f.Index); // 5
      f = Fractions.ByValue(0.125);
      Console.WriteLine(f); // Eighth 
      Console.WriteLine(Fractions.Count); // 7
      Console.WriteLine(Fractions.DynamicCount); // 2