Reputation: 2921
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
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
Reputation: 57670
You can use right shift operator too.
NodeLevel newLevel = (NodeLevel) ((int)currentLevel >> 1)
Upvotes: 6