Click here to Skip to main content
Click here to Skip to main content

Tree Structured Enumerations

, 2 Apr 2008 CPOL
Rate this:
Please Sign up or sign in to vote.
The way to maintain a tree structured enumeration while having all the advantages of the standard ones


In this article, I want to show you an approach of how a structured enumeration can be handled by C#.


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 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, I'm always having slight difficulties to find a good example, but here it is anyway.

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.

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 at them.


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 interest to us is the CreateList method. It obviously creates a list of the child enumeration values under a particular parental value. It will also allow us to use the output list for the display or various cycle purposes. I can imagine an iterator here.

public static List<ttype> CreateList<ttype>(TType parent)
    List<ttype> result = new List<ttype>();
    Type enumType = typeof (TType);
    TType[] enumValues = (TType[]) Enum.GetValues(enumType);
    foreach (TType enumValue in enumValues)
        if (IsChild(enumValue, parent))

    return result;

Some Examples of Use

This example took all I mentioned above and put it 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, ' ');
        DumpTree(animalKind, level + 1);

static void Main()
    DumpTree(AnimalKind.Unknown, 0);

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. The utility can also be extended with any kind of structuring routine which suits your need such as retrieving the chain of parents for a particular value.


  • The complex trees with many levels may find their limit because the indexing will reach the limit of enumeration (ulong). 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 be 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.


  • 2008-04-02: Missing example was added (Shall I ever get it right the first time?)
  • 2008-04-02: Initial article posted


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Smart K8
Software Developer
Czech Republic Czech Republic
Contacts: EMAIL -

Comments and Discussions

GeneralI did it my way (Part 1) [modified] PinmemberPIEBALDconsult10-Apr-08 18:22 
GeneralRe: I did it my way (Part 1) P.S. PinmemberPIEBALDconsult24-Apr-08 10:52 
GeneralOh, and... PinmemberPIEBALDconsult10-Apr-08 16:40 
GeneralC# 3.0 extension methods version PinmemberSmart K89-Apr-08 3:15 
GeneralRe: C# 3.0 extension methods version PinmemberPIEBALDconsult10-Apr-08 15:24 
GeneralClarify presentation PinmemberSeth Morris8-Apr-08 14:33 
Regardless of the active discussion of the technique (I like the overall idea a lot, personally), it took me a careful reading to "get" the meaning of the 100 value in the attribute.
A line or two of explanation might be a good addition. Maybe:
Enums with the Structured attribute can have their numeric values interpreted to get their parent. Some number of elements are reserved for possible children (the parameter to the Structured attribute) and numbers above that represent the parent.
For example, if the size is 10, the 3rd element is still 3, but its children are 3*10+0 to 3*10+9. The children of the second child of 3 is
(3*10+1)*10+0 to (3*10+1)*10+9
   Parent shifted left by the size to reserve
And clarify that in the code. Perhaps something like:
    [Structured(100)]  // 100 possible children per element 
    public enum AnimalKind
        Unknown         = 00000,
        DomesticAnimals = Unknown + 1, 
          Dog           = DomesticAnimals * 100 + 0,
            Dalmatin    = Dog * 100 + 0
            Greyhound   = Dog * 100 + 1,
            Malamute    = Dog * 100 + 2,
            Terrier     = Dog * 100 + 3,
          Cat           = DomesticAnimals * 100 + 1,
        WildAnimals     = Unknown + 2,
          Ape           = WildAnimals * 100 + 2,
            Chimpanzee  = Ape * 100 + 1,
            Gorrila     = Ape * 100 + 2,
            Orangutan   = Ape * 100 + 3,
          Deer          = WildAnimals * 100 + 1
Or even
    [Structured(100)]  // 100 possible children per element 
    public enum AnimalKind
        Unknown         = 00000,
        DomesticAnimals      = Unknown + 1, 
        DomesticAnimalParent = DomesticAnimal * 100
          Dog                = DomesticAnimalParent + 0,
          DogParent          = Dog * 100
            Dalmatin         = DogParent + 0
            Greyhound        = DogParent + 1,
            Malamute         = DogParent + 2,
            Terrier          = DogParent + 3,
          Cat                = DomesticAnimalParent + 1,
        WildAnimals          = Unknown + 2,
        WildAnimalParent     = WildAnimals * 100
          Ape                = WildAnimalParent + 2,
          ApeParent          = Ape * 100,
            Chimpanzee       = ApeParent + 1,
            Gorrila          = ApeParent + 2,
            Orangutan        = ApeParent + 3,
          Deer               = WildAnimalParent + 1
Also, rename CreateList to something less generic, like ChildrenOf:
    foreach (AnimalKind animalKind in EnumUtility.ChildrenOf(parent))
Finally, do you really want IsChild() to return true for enums without the [Structured] attribute? I'd expect an exception, or at least false.
AnswerRe: Clarify presentation [modified] PinmemberSmart K89-Apr-08 1:40 
GeneralSuggestions [modified] PinmemberPIEBALDconsult6-Apr-08 18:20 
GeneralSuggestions Part 2 PinmemberPIEBALDconsult6-Apr-08 19:11 
GeneralRe: Suggestions Part 2 PinmemberSmart K86-Apr-08 20:43 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150327.1 | Last Updated 2 Apr 2008
Article Copyright 2008 by Smart K8
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid