views:

56

answers:

2

Hey everyone,

I've got a .NET application running on WCF. In that application, I have a variety of "Types" defined ("CourseType", "PresentationType", "HierarchyType", etc) as enums. These are automatically synced with the database, so I can write nice code like:

public enum CourseType {
  Online = 1, 
  Classroom = 2
}

...

if(course.Type == CourseType.Online) {
  // do stuff on the server
}

I was wondering if anyone knew of a nice way to serialize the entire enum so I can write similar statements in JavaScript.

Note that I'm not asking about serializing just the value. What I want is to end up with some sort of JavaScript object that looks like:

CourseType = {
  'online' : 1,
  'classroom': 2
};

I could do this via reflection, I know, but I was hoping there was a built-in solution of some sort...

A: 

Using a JSON serializer with an anonymous type works really well in my opinion if the enum is relatively static and wont change often:

new { CourseType.Online, CourseType.Classroom }

But if you were looking for something to handle dynamic or multiple enums with no maintenance, you could create something that iterates over the name value pairs and creates a dictionary to be serialized (don't need reflection).

public static IDictionary<string, int> ConvertToMap(Type enumType)
{
  if (enumType == null) throw new ArgumentNullException("enumType");
  if (!enumType.IsEnum) throw new ArgumentException("Enum type expected", "enumType");

  var result = new Dictionary<string, int>();
  foreach (int value in Enum.GetValues(enumType))
    result.Add(Enum.GetName(enumType, value), value);

  return result;
}

Edit

If you need a JSON Serializer... I really like using JSON.NET http://james.newtonking.com/projects/json-net.aspx

Calgary Coder
A: 

Here ya go:

private enum CourseType
{
    Online = 1,
    Classroom = 2
}

private void GetCourseType()
{
    StringBuilder output = new StringBuilder();

    string[] names =
        Enum.GetNames(typeof(CourseType));

    output.AppendLine("CourseType = {");
    bool firstOne = true;
    foreach (string name in names)
    {
        if (!firstOne)
            output.Append(", " + Environment.NewLine);
        output.Append(string.Format("'{0}' : {1:N0}", name, (int)Enum.Parse(typeof(CourseType), name)));

        firstOne = false;
    }
    output.AppendLine(Environment.NewLine + "}");

    // Output that you could write out to the page...
    Debug.WriteLine(output.ToString());
}

This outputs:

CourseType = {
'Online' : 1, 
'Classroom' : 2
}
Robert Seder