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

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

    Join 1,437 other followers

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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

 
%d bloggers like this: