Sid Holland
Sid Holland

Reputation: 2921

How to "subtract 1" from a flags-type enum?

I have an enum defined as such:

[Flags]
public enum NodeLevel
{
    Root = 1,
    GroupLevel = 2,
    DeptLevel = 4,
    ClassLevel = 8,
    SubclassLevel = 16
}

I've defined it as Flags so that I can perform bitwise operations on them. Now I need to be able to "subtract 1" from the level so that given a specific level I can retrieve the next level up. For example, an object contains a value of NodeLevel.ClassLevel and I need to send NodeLevel.DeptLevel to a method.

Since NodeLevel newLevel = currentLevel - 1; doesn't work, does anyone have a suggestion as to how I can accomplish this? I imagine it's something absurdly simple but my brain won't come up with it at the moment.

I'm using .NET 2.0.

Upvotes: 0

Views: 1118

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1501163

Assuming you've only got a single flag, you can just divide by 2, with appropriate casting:

NodeLevel newLevel = (NodeLevel) ((int)currentLevel / 2);

(Interesting, you can add and subtract without any casting at all... but multiplication, division, shifting etc require casting both ways.)

Upvotes: 5

Shiplu Mokaddim
Shiplu Mokaddim

Reputation: 57670

You can use right shift operator too.

NodeLevel newLevel = (NodeLevel) ((int)currentLevel >> 1)

Upvotes: 6

Related Questions