C# - Shortcut for Multiple Enums in an if statement

Is there a way to take this enum check in C#:

enum ExampleEnum
{
	enum1 = 0, enum2, enum3, enum4, enum5, enum6, enum7, enum8, enum9, enum10
};
	
ExampleEnum currentState = enum1;
	
void ExampleFunction()
{
        //The code I'm currently using
	if(currentState != ExampleEnum.enum1  currentState != ExampleEnum.enum2  currentState != ExampleEnum.enum3)
	{
		
	}
}

And change it to something like this:

void ExampleFunction2()
{
	ExampleEnum stateCheck = enum1  enum2  enum3;
		
	if(currentState != stateCheck)
	{
			
	}
}

How about Enum Flags?

Flag itself doesn’t do much, and can be a bit misleading as it starts numbering at 0. The key is that you each value is a power of 2 so you can use bitwise operators.

Here’s a bit of a sample:

using UnityEngine;
using System.Collections;

public class FruitEnumTest : MonoBehaviour {

	// Use this for initialization
	void Start () {
		Test(FruitEnum.Apple);
		Test(FruitEnum.Banana);
		Test(FruitEnum.Orange);
		Test(FruitEnum.Pear);
		Test(FruitEnum.AppleOrPear);
		Test(FruitEnum.AnythingButAnOrange);	// Probably not the best way to use it.
	}
	
	
    void Test(FruitEnum fruit) {
		Debug.Log("Testing " + fruit);
  		if ((fruit  FruitEnum.AppleOrPear) == fruit) Debug.Log("It's an Apple or Pear"); 
		if ((fruit  FruitEnum.AppleOrPear) == FruitEnum.None) Debug.Log("It's not an Apple or Pear");
		if ((fruit  FruitEnum.Orange) == FruitEnum.None) Debug.Log("It's not an Orange");
		if ((fruit  FruitEnum.AllFruit) == fruit) Debug.Log("It's definitely something");
		Debug.Log("-----------------");
	}
}

public enum FruitEnum{
  None = 0,
  Apple = 1<<0,
  Pear = 1<<1,
  Orange = 1<<2,
  Banana = 1<<3,
  AllFruit = ~0,
  AppleOrPear = Apple | Pear,
  AnythingButAnOrange = AllFruit ^ Orange
}

… Yes work is slow today.

You could try using a List like:

void ExampleFunction2()
{
//It would be better to make this a class member instead of a local variable
	List<ExampleEnum> stateCheck = new List<ExampleEnum>() {enum1, enum2, enum3}; 
		
	if(!stateCheck.Contains(currentState))
	{
			...
	}
}
2 Likes

or you could just use a switch statement

switch would work for direct tests, but OP’s code wants to test for non-inclusion, and it could get to be messy cases