Search code examples
enumsimplementationmultiple-languages

Representation of enums


How do enums work 'behind the scenes' in programming languages? I am guessing that each language has a different way of representing these datatypes.

In java you can use the == operator, for example:

public class TestEnum {
   private enum Test {
      foo, bar
   }

   public static void main(String[] args) {
      System.out.println(Test.foo == Test.foo); // returns true
   }
}

Is an enum type converted to a primitive during the ==? Or is the enum value a Singleton? Does C# leverage enums in the same manner as java? Are database enum types treated differently compared to programming languages?


Solution

  • Java enums make use of a lot of tricks to still be objects but work with ==. The original typesafe enum pattern (see also Effective Java) can provide some insight, but the Enum.java source will show you exactly how they do it now.