First of all, you should apply Flags
attribute to your enum. That will indicate that enum can be treated as a set of flags:
[Flags]
enum VectorAxis
{
// Consider also adding value None = 0 when no axis ignored
X = 1,
Y = 2,
Z = 4
}
Now you can use bitwise operators with enum values:
SampleMethod(VectorAxis.X | VectorAxis.Y); // pass both axis using bitwise OR
How does it work? If you take a look on the binary representation of enum values
X = 001
Y = 010
Z = 100
When you apply bitwise OR operation to X
and Y
(result has a bit set to 1 if any of values have a bit set to 1 on the same position) you'll get 011
. And that's what will be passed to the method. In the method, you can check if the axis were passed using bitwise AND
public void SampleMethod(VectorAxis ignoredAxis)
{
if ((ignoredAxis & VectorAxis.X) == VectorAxis.X) // check using bitwise AND
// X is ignored
}
The result of bitwise AND (you have 1 only when both values have a bit set to 1 on same position) of passed value 011
and value of X 001
gives you back value of X
only when the corresponding bit is enabled in passed value.
011 & 001 = 001 // X is ignored
011 & 010 = 010 // Y is ignored
011 & 100 = 000 // Z is not ignored
Also instead of checking value manually, you can use Enum.HasFlag
method which does the same
if (ignoredAxis.HasFlag(VectorAxis.X))