Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 897
Stickly Avatar asked Oct 18 '13 19:10

Stickly


People also ask

Do enums have to be unique?

Enum names are in global scope, they need to be unique.

What is enum ts?

In TypeScript, enums, or enumerated types, are data structures of constant length that hold a set of constant values. Each of these constant values is known as a member of the enum. Enums are useful when setting properties or values that can only be a certain number of possible values.

What are the two types of unary operators?

The Unary decrement operator is of two types: the Pre decrement operator and the Post Decrement operator.


1 Answers

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.

like image 124
Tim S. Avatar answered Oct 05 '22 19:10

Tim S.