There’s not a ton to be found online for this, but it’s handy (or even required) for certain ASP.NET things such as treeviews or – in my case – a DevExpress navbar menu. This is a quick and dirty rundown on how to implement the interfaces accordingly.

We need three things for this: a MenuItem class, a MenuItemCollection class, and a source for the menu items. For this, we’ll just create the menu sources via code, but they could be pulled out of a db or wherever.

Use the System.Web.IU namespace to have access to the interfaces (why this resides in System.Web instead of a more universal lib, I don’t know).

The MenuItem Class

The MenuItem itself needs to implement the IHierarchyData interface. Hierarchy data, such as a menu item, usually has an ID and some sort of ParentID, so we’ll include that. Furthermore, DevExpress requires a Text and NavigateUrl property for autoprop matching, so those will be in there as well. Note that some of the methods will not be filled out until later.

This is a basic class with the IHierarchyData interface implemented.

The MenuItemCollection Class

Very straightforward here:

This provides a collection to be enumerated.

The MenuItemsSource Class

This can be whatever, but in this case it provides static methods to get a) all menu items, as well as b) just the root items (note that the roots are defined as having a ParentID of 0: this could (should) be refactored to allow for nullable values, or even object-based parents rather than IDs, depending on the source).

Now at any point your components require an IHierarchyData or IHierarchicalEnumerable interface, you can pass it a collection of MenuItemCollection to do the job.