Click here to Skip to main content
13,352,175 members (72,357 online)
Click here to Skip to main content
Add your own
alternative version


14 bookmarked
Posted 2 Apr 2008

Tree Structured Enumerations

, 2 Apr 2008
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 -

You may also be interested in...

Comments and Discussions

AnswerRe: Reinventing the wheel Pin
Smart K82-Apr-08 11:35
memberSmart K82-Apr-08 11:35 
GeneralRe: Reinventing the wheel Pin
leppie2-Apr-08 12:10
member leppie 2-Apr-08 12:10 
GeneralRe: Reinventing the wheel Pin
Smart K82-Apr-08 12:35
memberSmart K82-Apr-08 12:35 
GeneralRe: Reinventing the wheel Pin
peterchen2-Apr-08 20:30
memberpeterchen2-Apr-08 20:30 
GeneralRe: Reinventing the wheel Pin
Smart K82-Apr-08 20:53
memberSmart K82-Apr-08 20:53 
GeneralRe: Reinventing the wheel Pin
Smart K82-Apr-08 22:22
memberSmart K82-Apr-08 22:22 
GeneralRe: Reinventing the wheel Pin
PIEBALDconsult5-Apr-08 18:17
memberPIEBALDconsult5-Apr-08 18:17 
GeneralRe: Reinventing the wheel Pin
Smart K85-Apr-08 22:38
memberSmart K85-Apr-08 22:38 
PIEBALDconsult wrote:
Smart K8 wrote:

Whether you'll choose hexadecimals over decimals or high-ordering over low-ordering is not a concern of this article as much. Rather it is a normalized way to reconstruct a tree from the enumerations with different granularities.

Yes, but it should also be fairly efficient and maintainable, and I suspect that having the class (or whatever) value shift around is the opposite of that.

You surely are right on the point of efficiency and maintainability. I was just answering to leppie who didn't get that this idea is not a reinventing the wheel and it is not possible to structure the tree using the bitwise masks this will only get you all the parents but not an immediate one.

Smart K8 wrote:

Now try to use ONE method to reconstruct the tree for both enumerations.

Now that it's the weekend I have more time to think about this. So what form should the tree take?

I guess before we address that; what functions should be available?

Basically you should have the EnumType.IsChild(EnumType parent) which will detect if a specified enumeration value is a child of a specific direct parent (I'll try to elaborate on the Extension methods in C# if there is a way to extend the enumerations via System.Enum but I guess it is not possible). The listing method is only the cream on the top of it. With the IsChild (or an alternative method) you should be able to reconstruct a tree (either visual one or non-visual one). That's the main point of the article. If there's better way of achieving that with enumerations in different hierarchy style (either low-ordering) it will be an improvement (and I'll be happy to hear about it).


The wisdom is to see things truthfully.

GeneralRe: Reinventing the wheel Pin
PIEBALDconsult5-Apr-08 19:13
memberPIEBALDconsult5-Apr-08 19:13 
GeneralRe: Reinventing the wheel Pin
PIEBALDconsult6-Apr-08 18:22
memberPIEBALDconsult6-Apr-08 18:22 

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

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

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