I would find it convenient to have something like this (contrived example):
enum Animal
{
Mammal
{
Cat,
Dog,
Bear
},
Bird
{
Pigeon,
Hawk,
Ostrich
},
Fish
{
Goldfish,
Trout,
Shark
}
};
Sometimes I want the class hierarchy but sometimes I really don't. Use case would be something like this:
var creature1 = Animal.Bird.Hawk;
Animal creature2 = Animal.Mammal; //OK
creature1 == Animal.Bird; // false
creature1 is Animal.Bird; // true
creature1 is Animal; // true
Barely useful, as you can write
enum Animal
{
Mammal_Cat,
Mammal_Dog,
Mammal_Bear
...
};
and with intellisense you get the same benefits.
Beside of this, CLR probably do not allow for these enhancements, and here must be implemented significant trickery to smoothly move these enums between sources and libraries.
Well, the intellisense benefits are of no use to me, since I wanted to react differently based on the enum's value and "parent value" at runtime. This is the use case very similar to what I have in mind, and yes the solutions are "ugly" with "muddy intent".
http://stackoverflow.com/questions/980766/how-do-i-declare-a-nested-enum
As for the CLR not allowing it smoothly, that I can understand.
You could achieve this in F# with discriminated unions, but I would love to see this made possible in C# also
Check out #6739.
Normal C#/CLR enums can only be simple integral primitive types. Short of getting funky with bitmasks I don't see how a hierarchical relationship could be established through them. Discriminated unions would be a better feature.
This can be represented by flags enum reasonably well
C#
[Flags]
enum Animal
{
//Groups
Mammal = 0x1,
Bird = 0x2,
Fish = 0x4,
//Mammals
Cat = 0x101,
Dog = 0x201,
Bear = 0x401,
//Birds
Pigeon = 0x102,
Hawk = 0x202,
Ostrich = 0x402
//Fishes
Goldfish = 0x104,
Trout = 0x204,
Shark = 0x404,
};
You can check for presence in group by calling var isBird = someAnimal.HasFlag(Animal.Bird);.
Also with binary literals in C#7, this will be even easier to write.
This looks very similar to https://github.com/dotnet/roslyn/issues/13192.
There is a similar request in https://github.com/dotnet/csharplang/issues/587
Most helpful comment
Check out #6739.
Normal C#/CLR enums can only be simple integral primitive types. Short of getting funky with bitmasks I don't see how a hierarchical relationship could be established through them. Discriminated unions would be a better feature.