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.
There is nothing that requires them to be sequential. Your enum definition is fine and will compile without issue.
No they cannot. They are limited to numeric values of the underlying enum type. +1 Good one with the helper method! ToString("F") is useful for formatting to the name of the enum value, if they don't want custom strings.
If the enum is only used within one class, it should be placed within that class, but if the enum is used between two or more classes, it ought to either be in it's own code file, or in a conglomerated code file that contains all the enum for a particular assembly.
Since there is no problem with a type that contains an multiple constants that have the same value, there is no problem with the enum definition. But since the enum does not have unique values you might have an issue when converting into this enum.
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);
Do-it-yourself solution:
class Cars
{
private static int CurrentId = 0;
private readonly int id;
private Cars()
{
id = CurrentId;
CurrentId++;
}
public static class Ford
{
public static Cars Corsair = new Cars();
public static Cars Cortina = new Cars();
public static Cars Galaxy = new Cars();
public static Cars GT = new Cars();
}
public static class Ferrari
{
public static Cars Testarossa = new Cars();
public static Cars California = new Cars();
public static Cars Enzo = new Cars();
}
// Add overrides of Equals and GetHash from id
}
You will lose all features contained in Enums
class this way. But that is understandable, because you want logic that is not normally supported.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With