Jack Jack - 3 months ago 16
C# Question

Is it possible to create hierarchical enums?

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.

Answer

I thought about answering this with extensions and/or ICustomEnum stuff.

Then I thought - is there anything really that bad with the following? :-)

    enum Cars
    {
       Ford_Corsair,
       Ford_Cortina,
       Ford_Galaxy,
       Ford_GT,

       Ferrari_Testarossa,
       Ferrari_California,
       Ferrari_Enzo,
    }

Your function still looks like:

public void BuildCar(Cars car);

Your call looks like:

BuildCar(Cars.Ferrari_Enzo);
Comments