The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Email Subscription

    Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 716 other subscribers

.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:

[sourcecode language=”csharp”]
namespace BeSharp
{
enum TwoState
{
False = 0,
True = 1,
}
enum ThreeState
{
False = 0,
True = 1,
Unknown = -1,
}
}
[/sourcecode]

Well, you can do it like this too, since Operations between different enum types are allowed in another enum declaration:

[sourcecode language=”csharp”]
namespace BeSharp
{
enum TwoState
{
False = 0,
True = 1,
}
enum ThreeState
{
False = TwoState.False,
True = TwoState.True,
Unknown = -1,
}
}
[/sourcecode]

You cannot use this outside enum declarations however, so it is impossible to write something like this:

[sourcecode language=”csharp”]
namespace BeSharp
{
class Program
{
public static void Main()
{
ThreeState value = ThreeState.False;
if (value == TwoState.False)
Console.WriteLine("False");
}
}
}
[/sourcecode]

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

 

Discover more from The Wiert Corner - irregular stream of stuff

Subscribe now to keep reading and get access to the full archive.

Continue reading