Adding a method to an enum.

Jonathan M Davis jmdavisProg at gmx.com
Sun Jun 19 20:12:31 PDT 2011


On 2011-06-19 19:48, Charles McAnany wrote:
> Hi, all. I'm looking for a way to make constants that have methods
> without a lot of overhead. In particular, a way to define a
> Direction and then be able to rotate it right. Here's kind of what I
> have in mind:
> 
> enum Direction{
> left, right, up, down;
> 
> public Direction rotateRight(){
>  switch(this){
>  case left:
>    return up;
>  case up:
>    return right;
>  case right:
>    return down;
>  case down:
>    return left;
>  }
> }
> 
> 
> The best I can think of is to make a new method, which isn't
> terrible, but not elegant, either.
> Any thoughts?

Well, you can have a function like that no problem. But you can't add it to an 
enum. It's just a free-standing function which takes an enum and returns the 
Direction to its right.

Now, in theory, you could define an enum which was a struct which had a 
function which returned the Direction to the right, but you can't currently 
have enums of struct type with more than one value ( 
http://d.puremagic.com/issues/show_bug.cgi?id=4423 ), though it's supposed to. 
Of course, defining such a function could be entertaining given that it would 
effectively be recursive in nature as far as its definition goes (since each 
enum would be of the struct type and wouldn't exist unless the struct type can 
be instantiated, but the struct type couldn't have such a function unless it 
could be instantiated...). So, I don't know if you could get it to work with a 
struct anyway.

The simplest thing to do is to simply have a free function which takes a 
Direction and returns the Direction to its right. There shouldn't be any need 
to be able to call the function on the enum itself.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list