Click to See Complete Forum and Search --> : Overloading operators with Enums?


wsmmi6674
May 3rd, 2005, 03:12 PM
Is it possible to overload an operator with both the addend and augend (lhs & rhs) as user defined enum types? I have two enums defined as:

public enum Rotate
{
CLOCKWISE,
COUNTER_CLOCKWISE
}
public enum Direction
{
NORTH,
EAST,
SOUTH,
WEST
}


And I'd like to be able to do this:

Direction d = Direction.NORTH;
d += Rotate.CLOCKWISE;
// Now d should be Direction.EAST

d += Rotate.COUNTER_CLOCKWISE;
d += Rotate.COUNTER_CLOCKWISE;
// Now d should be Direction.WEST


I am new to C# (obviously). If this is possible, what is the syntax?

Thanks,
--
Scott

pete#
May 3rd, 2005, 06:51 PM
Hi Scott,

Great idea. I think you will run into problems trying to handle this exclusively using enums, since the direction attirbute will be assigned an enum based on the initial setting. If you are going through rotations then you will eventually go out of the bounds of the enum.

eg. Say north = 0, east =1, south = 2, and west = 3. What happens when you rotate clockwise at west? You end up with a value of 4 which is not covered.

The next approach would be to take a modulus of the result which would give you 0 in the example below, but then if you rotated counter clockwise from north you end up with a -1. You can't use the absolute value of this or you end up with east again instead of west...

I'm afraid the best solution here is to create a direction class.

Keep your enums inside the class, and provide a "Value" property which returns the current rotation.

Then provide 2 method, rotate clockwise and rotatecounterclockwise, which alter the direction based on current direction. You could even provide overloaded methods to rotate more than once etc.

Hope that helps.

Good luck,
Pete

wsmmi6674
May 4th, 2005, 08:50 AM
Thanks, Pete.

I was guessing that a class was the only way to do what I want. Its a bit more work, with more overhead, but it will get the job done. Ideally, I'd like to do this:


public static Direction operator+(Direction lhs, Rotate rhs)
{
if (rhs == Rotate.CLOCKWISE)
{
++lhs;
if (lhs > Direction.WEST)
lhs = Direction.NORTH;
}
else
{
--lhs;
if (lhs < Direction.NORTH)
lhs = Direction.WEST;
}
return lhs;
}


But since I can't put mthods into an enum, and global methods are not allowed in C#, some kind of Direction class is the only way to go.
--
Scott