|
-
May 3rd, 2005, 03:12 PM
#1
Overloading operators with Enums?
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:
Code:
public enum Rotate
{
CLOCKWISE,
COUNTER_CLOCKWISE
}
public enum Direction
{
NORTH,
EAST,
SOUTH,
WEST
}
And I'd like to be able to do this:
Code:
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
-
May 3rd, 2005, 06:51 PM
#2
Re: Overloading operators with Enums?
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
101010
-
May 4th, 2005, 08:50 AM
#3
Re: Overloading operators with Enums?
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:
Code:
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
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|