In this article I want to show you an approach of how can a structured enumeration be handled by the C#.
Background
While playing with my little home project I stumbled upon a problem of having all those category enumerations displayed in a tree. I wanted to keep it simple - as the enumerations are - while avoiding the need to create the structured object hierarchies for every one of them. So after a bit of thinking I came up with this solution. I hope you'll find it useful or at least interesting.
Structured enumeration
First we have to tickle our old plain list enumeration a bit and convert it to a structured one. I chose the animal categories.. well.. to confess myself I'm always having the slight difficulties to find out a good example but here it is anyway.
[Structured(100)]
public enum AnimalKind
{
Unknown = 00000,
DomesticAnimals = 00001,
Dog = 00100,
Dalmatin = 10000,
Greyhound = 10001,
Malamute = 10002,
Terrier = 10003,
Cat = 00101,
WildAnimals = 00002,
Ape = 00200,
Chimpanzee = 20000,
Gorrila = 20001,
Orangutan = 20002,
Deer = 00201
}
As you might notice some unknown attribute is used there. Let me introduce it to you.
[AttributeUsage(AttributeTargets.Enum)]
public class StructuredAttribute : Attribute
{
public int span;
public int Span
{
get { return span; }
set { span = value; }
}
public StructuredAttribute(int span)
{
this.span = span;
}
}
This simple attribute is composed of only one property (an automatic property may be used in C# 3.0, god I love those). The attribute is responsible for determining the span (multiplicator) of the tree levels thus allowing us to distinguish the hierarchy later.
Well.. later is now because this ought to be a short article. I took the liberty to create the utility class to help us deal with the structured enumerations. It consists of two static methods. Let's take a closer look on them.
Methods
The IsChild method is used to determine if one enumeration value is placed under another one. I guess the utility can be easily extended by a method determining the whole chain of the parents from a particular enum value.
public static bool IsChild<ttype>(TType child, TType parent)
{
Type enumType = typeof(TType);
Object[] attributeList = enumType.GetCustomAttributes(typeof(StructuredAttribute), true);
if (attributeList.Length > 0)
{
StructuredAttribute attribute = (StructuredAttribute)attributeList[0];
int span = attribute.Span;
int parentIndex = (int)Convert.ChangeType(parent, typeof(int));
int childIndex = (int)Convert.ChangeType(child, typeof(int));
int index = childIndex / span;
return (index == parentIndex && childIndex != parentIndex);
}
return true;
}
Another useful method that may be of our interest is the CreateList method. It obviously creates a list of the child enumeration values under a particular parental value. It will also allow as to use the output list for the display or various cycle purposes. I can imagine an iterator here.
public static List CreateList(TType parent)
{
List result = new List();
Type enumType = typeof (TType);
TType[] enumValues = (TType[]) Enum.GetValues(enumType);
foreach (TType enumValue in enumValues)
{
if (IsChild(enumValue, parent))
{
result.Add(enumValue);
}
}
return result;
}
Some examples of use
This example took all I mentioned above and put it in to use. It will dump the tree to a console output while making the levels indented.
private static void DumpTree(AnimalKind parent, Int32 level)
{
foreach (AnimalKind animalKind in EnumUtility.CreateList(parent))
{
string caption = animalKind.ToString();
int width = caption.Length;
string output = caption.PadLeft(width + level, ' ');
Console.WriteLine(output);
DumpTree(animalKind, level + 1);
}
}
static void Main()
{
DumpTree(AnimalKind.Unknown, 0);
Console.ReadKey();
}
Possible enhancements
1. As I said earlier in this article. I can imagine some kind of iterator (or perhaps an indexer) instead of the CreateList method.
2. The default indexing capabilities of enumerations can be widened by "inheriting" the enumeration from ulong type instead of default uint.
3. Also the utility can be extended with any kind of structuring routine which suits your need. Such as retrieving the chain of parents for a particular value.
Limitations
* The complex trees with many levels may find their limit because the indexing will reach the limit of enumeration (ulong it is). This limitation can be reduced by lowering the span value on the attribute thus allowing to scale for the count of branches against the count of levels.
* It is recommended to use some default (zero) value which will then used to retrieve the level one branches.
Personal note
I found these structured enumerations quite useful myself dealing with countless - now waiting to be structured - category enumerations. They cut the time needed to create the editable trees where the categories are distinguished from the instance items. Moreover the enumeration is still one type in the end.
Good luck and I will be pleased to hear your comments.