Search code examples
c#enumsoperatorsunary-operator

Is there a way to implement unary operators for enum types?


I have the following:

MovingDirection.UP;

and I want to use the ! operator as follows:

!MovingDirection.Up; // will give MovingDirection.Down

(it's an Enum)

I have tried:

public static MovingDirection operator !(MovingDirection f)
{
    return MovingDirection.DOWN;
}

... but I receive an error:

Parameter type of this unary operator must be the containing type

Any ideas?


Solution

  • No, you can't implement methods or operators on enums. You can create an extension method:

    public static MovingDirection Reverse(this MovingDirection direction)
    {
        // implement
    }
    

    Use like:

    MovingDirection.Up.Reverse(); // will give MovingDirection.Down
    

    Or you can use an enum-like class instead of an actual enum.