|
I'm not usually one to follow up replies from another's blog in my own, but some challenges need further analysis. Ayende posted earlier about emulating the behavior of Java Enums in .NET . Since the inception of C#, there has been a lot of back and forth between Java and C# in terms of features such as generics, attributes (annotations), foreach statements, and lastly enums. There are significant differences between the two, but let's see if we can bridge that gap. Enter Java Enums Previous to Java 5.0, Java had a standard way of delcaring an enumerated type as a constant. This was neither type safe, brittle and rather uninformative (what does 3 mean anyways?). Finally, come 5.0, this feature was added to have simple enums such as we've had in C# all along. But, unlike C#, these were not capable of being cast to an integer, unsigned or otherwise. A simple enum could look something like this. public enum PriorityLevel { Low, Medium, High } Not only can they hold the value just as C/C++/C# enums can, they can also hold behavior and data. Let's expand our PriorityLevel to hold an integer level equivalent. public final enum PriorityLevel { Low( "Low Priority" ), Medium( "Medium Priority" ), High( "High Priority" ); private static final Map<String,Status> lookup = getLookup(); private static HashMap<String, PriorityLevel> getLookup() { HashMap<String, PriorityLevel> l = new HashMap<String,PriorityLevel>(); for (PriorityLevel p : EnumSet.allOf(PriorityLevel. class )) l.put(p.getLevel(), p); return l; } private String level; private PriorityLevel(String level) { this .level = level; } public String getLevel() { return level; } public static PriorityLevel get(String level) { return lookup.get(level); } } This gives us the ability to define a string equivalent for our given enum value. This can be a powerful concept that the data is not just limited to integers. So, this had me thinking about the possibilities of this in .NET. Enter C# 3.0 and Extension Methods Given that the ability of the Java enum has the ability to map itself to another data type's equivalent quite easily, it was a matter of time before we tried something like that in C#. With the birth of extension methods, we have the ability to add features onto given types, such as enums. An example of taking the above example and using extension methods might look like this. public enum PriorityLevel { Low, Medium, High } public static class Extensions { public static string GetLevel( this PriorityLevel level) { switch (level) { case PriorityLevel...
|