.NET/C#: fun with enums and aliases part 2
Posted by jpluimers on 2014/01/29
In the .NET/C#: fun with enums and aliases part 1 you saw that an enumerated type can specify an underlying type.
The underlying type is limited to a strict set of built-in C# types: , so you cannot use a CTS type for it.
So you might think that you can only define enumeration values by integer constant like this:
namespace BeSharp
{
enum TwoState
{
False = 0,
True = 1,
}
enum ThreeState
{
False = 0,
True = 1,
Unknown = -1,
}
}
Well, you can do it like this too, since Operations between different enum types are allowed in another enum declaration:
namespace BeSharp
{
enum TwoState
{
False = 0,
True = 1,
}
enum ThreeState
{
False = TwoState.False,
True = TwoState.True,
Unknown = -1,
}
}
You cannot use this outside enum declarations however, so it is impossible to write something like this:
namespace BeSharp
{
class Program
{
public static void Main()
{
ThreeState value = ThreeState.False;
if (value == TwoState.False)
Console.WriteLine("False");
}
}
}
The enum fun goes on even further: you can use any operator compatible with enums for declaring your values, and even mix/match types. Like enum Animal { Giraffe = Fruit.Apple * Shape.Square << DayOfWeek.Thursday, }
–jeroen






Leave a comment