Is it possible to create hierarchical enums?

Viewed 8139

I want to create a hierarchical enum that represents a type that I can pass as a parameter.

The data structure looks like this:

enum Cars
{
   Ford { Corsair, Cortina, Galaxy, GT },
   Ferrari { Testarossa, California, Enzo },
   ...
}

I wish to call a function with the following signature:

public void BuildCar(Cars car);

Like this:

BuildCar(Cars.Ferrari.Enzo);

Basically, I want to enforce the car/manufacturer relationship in the type.

6 Answers

I have built some sort of nested enum using Custom Attributes

public class MyParentTypeAttribute : Attribute
{
    public MyParentType MyParentType { get; protected set; }

    public MyParentTypeAttribute(MyParentType myParentType)
    {
        MyParentType = myParentType;
    }
}



public enum MyParentType 
{ 
    Parent1,
    Parent2
}




public enum MyChildType
{
    [MyParentType(MyParentType.Parent1)]
    Child1,

    [MyParentType(MyParentType.Parent1)]
    Child2,
    
    [MyParentType(MyParentType.Parent1)]
    Child3,
    
    [MyParentType(MyParentType.Parent2)]
    Child4,
    
    [MyParentType(MyParentType.Parent2)]
    Child5
}

You can then create some easy methods to check which ParentType is related to the child type... Might not be the nicest way, but it works.

Related