my6solutions

asp .net, the social web & other distractions

 

Running Apps


PayPal - The safer, easier way to pay online!

Disclaimer

I am in no way affiliated with Microsoft or Google. I am just another developer trying to make a difference. All opinions and observations are usually my own.

Mimicking Java enumerations in C#

In java, enumerations are actually classes. Thus, the java enumeration will allow methods, fields and interfaces. In C#, an enum is an enum. Nothing more, nothing less. However, we can achieve similar functionality to the Java enumerations via extension methods. For example, the following is a java enumeration.

    1 public static enum Field {

    2     /** the field name for mimeType. */

    3     MIME_TYPE("mimeType"),

    4     /** the field name for type. */

    5     TYPE("type"),

    6     /** the field name for url. */

    7     URL("url"),

    8     /** the thumbnail Url */

    9     THUMBNAIL_URL("thumbnailUrl");

   10 

   11     /**

   12      * The field name that the instance represents.

   13      */

   14     private final String jsonString;

   15 

   16     /**

   17      * create a field base on the an element name.

   18      *

   19      * @param jsonString the name of the element

   20      */

   21     private Field(String jsonString) {

   22       this.jsonString = jsonString;

   23     }

   24 

   25     /**

   26      * @return a string representation of the enum.

   27      */

   28     @Override

   29     public String toString() {

   30       return this.jsonString;

   31     }

   32   }

To achieve the same functionality in C#, the following can be utilised

    1 public enum Field

    2 {

    3    [Description("mimeType")]

    4    MIME_TYPE,

    5    [Description("type")]

    6    TYPE,

    7    [Description("url")]

    8    URL,

    9    [Description("thumbnailUrl")]

   10     THUMBNAIL_URL

   11 }

And we define the following extension method to allow us to use the string specified by the DescriptionAttribute.

    1 public static class EnumHelper

    2     {

    3         /// <summary>

    4         /// Returns string specified by DescriptionAttribute, otherwise do the usual ToString()

    5         /// </summary>

    6         /// <param name="name"></param>

    7         /// <returns></returns>

    8         public static string ToDescriptionString(this Enum obj)

    9         {

   10             var attribs = (DescriptionAttribute[])obj.GetType().GetField(obj.ToString()).GetCustomAttributes(typeof (DescriptionAttribute), false);

   11             return attribs.Length > 0 ? attribs[0].Description : obj.ToString();

   12         }

   13     }

I reckon this is a cleaner method, compared to the use of an EnumBaseType<>, eg.

    1 public abstract class EnumBaseType<T> where T : EnumBaseType<T>

    2     {

    3         private static readonly HashSet<T> enumValues = new HashSet<T>();

    4 

    5         public readonly int Key;

    6         public readonly string JsonValue;

    7         public readonly string Value;

    8 

    9         public EnumBaseType()

   10         {

   11 

   12         }

   13         public EnumBaseType(int key, string value)

   14         {

   15             Key = key;

   16             Value = value;

   17             enumValues.Add((T)this);

   18         }

   19         public EnumBaseType(string key, string value)

   20         {

   21             JsonValue = key;

   22             Value = value;

   23             enumValues.Add((T)this);

   24         }

   25     }

Now to see if I can completely remove the use of the EnumBaseType<> from my projects.

Bookmark and Share

Categories: ASP .NET
Permalink | Comments (1) | Post RSSRSS comment feed

Comments

Filip

Saturday, July 11, 2009 4:32 PM

Filip

I had a similar problem with descriptions on C# enums, but I ended up taking a different approach. Reflection proved to be quite slow, so I turned to code generation.
I define my enums in an XML file, and each enum class item can have metadata (sub elements in XML tree). I then use a simple NVelocity template to render C# source for enum, and for its corresponding extension class with a GetDescription method.
Works like a charm, especially since you can integrate it with MSBuild to do generation as part of build.
You may try doing something similar with T4 templates.