Impostor
Impostor

Reputation: 2050

Unexpected behavior of enum

I implemented a method with System.Drawing.RotateFlipType and got a strange behaviour while comparing values.

System.Drawing.RotateFlipType item1 = System.Drawing.RotateFlipType.RotateNoneFlipNone;
System.Drawing.RotateFlipType item2 = System.Drawing.RotateFlipType.Rotate180FlipXY;
Console.WriteLine(item1 == item2); //true

How could this be true?

Upvotes: 1

Views: 211

Answers (3)

Wai Ha Lee
Wai Ha Lee

Reputation: 8815

As canton7 pointed out in a comment,

If you think about it, it makes sense. "Specifies a 180-degree clockwise rotation followed by a horizontal and vertical flip." Do that transformation in your head, and you end up back where you started.

For that reason, the RotateFlipType values RotateNoneFlipNone and Rotate180FlipXY both have the same value (of 0) (API source).

This is made apparent in the reference source (with the XML comments elided):

public enum RotateFlipType
{
    RotateNoneFlipNone = 0,
    Rotate90FlipNone   = 1,
    Rotate180FlipNone  = 2,
    Rotate270FlipNone  = 3,
    RotateNoneFlipX    = 4,
    Rotate90FlipX      = 5,
    Rotate180FlipX     = 6,
    Rotate270FlipX     = 7,
    RotateNoneFlipY    = Rotate180FlipX,
    Rotate90FlipY      = Rotate270FlipX,
    Rotate180FlipY     = RotateNoneFlipX,
    Rotate270FlipY     = Rotate90FlipX,
    RotateNoneFlipXY   = Rotate180FlipNone,
    Rotate90FlipXY     = Rotate270FlipNone,
    Rotate180FlipXY    = RotateNoneFlipNone,
    Rotate270FlipXY    = Rotate90FlipNone
}

There's no harm in having the duplicates, so I suppose it makes it easier for the consumers of the enum to have multiple definitions for the same thing.

In fact there's no reason that you can't have duplicate numeric values for enum values - in fact the C# language specification says:

Multiple enum members may share the same associated value. The example

enum Color 
{
    Red,
    Green,
    Blue,
    Max = Blue
}

shows an enum in which two enum members—Blue and Max—have the same associated value.

Upvotes: 4

Patrick Hofman
Patrick Hofman

Reputation: 157118

RotateNoneFlipNone and RotateNoneFlipXY both have value 0.

//
// Summary:
//     Specifies no clockwise rotation and no flipping.
RotateNoneFlipNone = 0,
//
// Summary:
//     Specifies a 180-degree clockwise rotation followed by a horizontal and vertical
//     flip.
Rotate180FlipXY = 0,

There are actually more of them, and it makes perfectly sense. Like rotating 270 clockwise or 90 anti-clockwise, it is all the same.

Upvotes: 3

Related Questions