Make sure the enumeration is in one of the desired states

If I have an enumeration

[Flags] public enum GameFlow { Normal = 1, NormalNoMove = 2, Paused = 4, Battle = 8 } 

Is it possible to check if an enumeration in one of the desired states is with one check? For example, if I want to check if an enumeration is normal or NormalNoMove, I should always write it like this:

 if(Flow == GameFlow.Normal || Flow == GameFlow.NormalNoMove) 

This is not a big problem if there are only two values, but there will be more enumeration states, and it would be nice if I only had to change it in one place. Is it possible to make an alum alias that returns true if the enum value is either normal or NormalNoMove? Or do I need to write some kind of helper method to achieve this (extension method?)

+6
source share
3 answers

Bitwise logic should work with flag enums like this.

 if((Flow & (GameFlow.Normal | GameFlow.NormalNoMove)) > 0) 

You can also create enum values โ€‹โ€‹that combine other values, as I mention here .

So in your case:

 [Flags] public enum GameFlow { Normal = 1, NormalNoMove = 2, Paused = 4, Battle = 8, AnyNormal = Normal | NormalNoMove } bool IsNormal(GameFlow flow) { return (flow & GameFlow.AnyNormal) > 0; } 

And the LINQPad test:

 void Main() { IsNormal(GameFlow.Normal).Dump();// True IsNormal(GameFlow.NormalNoMove).Dump();// True IsNormal(GameFlow.Paused).Dump();// False IsNormal(GameFlow.Battle).Dump();// False IsNormal(GameFlow.Normal | GameFlow.Paused).Dump();// True IsNormal(GameFlow.NormalNoMove | GameFlow.Battle).Dump();// True IsNormal(GameFlow.Paused | GameFlow.Battle).Dump();// False IsNormal(GameFlow.Battle | GameFlow.Normal).Dump();// True } 

Based on your comment, I wonder if bit-wise flags need to be reviewed here. It appears that โ€œNormalโ€ is the state you want to check, and โ€œNormalNoMoveโ€ is based on that. Perhaps your listing should look like this:

 [Flags] public enum GameFlow { Normal = 1, NormalNoMove = Normal | 2, Paused = 4, Battle = 8 } 

This way you can check if flow & GameFlow.Normal > 0 is there if you are in a normal state: NormalNoMove just "extends" Normal , so to speak.

+7
source

Based on the comment on @StringlingWarrior's answer, you can simply create an extension method that will shorten your code:

 public static class GameFlowExtensions { public static bool IsNormal(this GameFlow flow) { return (flow & (GameFlow.Normal | GameFlow.NormalNoMove)) > 0; } } // usage: if (Flow.IsNormal()) 
+1
source

You can set the variable equal to GameFlow.Normal and GameFlow.NormalNoMove , and then compare the value you have, like this:

 GameFlow NormalOrNormalNoMove = GameFlow.Normal | GameFlow.NormalNoMove; ... if ((Flow & NormalOrNormalNoMove) > 0) { // Your code } 
+1
source

Source: https://habr.com/ru/post/950843/


All Articles