Wednesday, May 23, 2007

Documenting Enum Values

If you maintain a codebase that is of any decent size, chances are you'll have defined a fair few enum types. You may also need these types and their values to be documented somewhere, as not everyone who needs them could have access to the code where they are defined.

You could of course do this manually, but if you already have lots of types this could be tedious. Luckily its quite simple to write something that will do this for you.

The code below takes a parameter for the assembly path and name, and writes the values to the Console.



private static void DumpAssemblyEnums(string assemblyPath)
{
StringBuilder builder = new StringBuilder();

// flag to check if we should put the string we
// create into the Console output
bool hasEntriesToShow = false;
try
{
builder.AppendLine(string.Format("===== {0} =====", assemblyPath));

// load assembly from the path
Assembly assembly = Assembly.LoadFrom(assemblyPath);

// get the types from this assembly
Type[] assemblyTypes = assembly.GetTypes();

for (int i = 0; i < assemblyTypes.Length; i++)
{
try
{
// check if the type is an enum
if (assemblyTypes[i].IsEnum)
{
hasEntriesToShow = true;

// output the full type name of this enum
builder.AppendLine(
string.Format("==== {0} ====",
assemblyTypes[i].FullName));

// get the values for the enum type
Array array = Enum.GetValues(assemblyTypes[i]);

// loop through the array
for (int j = 0; j < array.Length; j++)
{
// output the numeric value by converting to a
// long
// use long as enum values can be larger than
// an int
builder.AppendLine(
" " + Convert.ToInt64(array.GetValue(j)) +
" = " + array.GetValue(j).ToString());
}
builder.AppendLine();
}
}
catch (Exception ex)
{
// output any error
builder.AppendLine("**ERROR: " + ex.Message + "**");
}
}
}
catch (Exception ex)
{
// output any error
builder.AppendLine("**ERROR: " + ex.Message + "**");
}

// push to Console stream if we've got something to show
if (hasEntriesToShow)
Console.Write(builder.ToString());
}



You can call this directly, or use a directory traversal to output all enum values in all assemblies in a directory.

This example will output into a format which can be used on a Wiki page, but you can edit it to output in any format you like.

No comments: