Enum Tricks

31 03 2014

Short post. It’s 1.18am and my two main projects are both running high which means a lot less time for anything else.

A couple of little tricks for flag enumerations; nothing fancy but useful.

Say we have an enum representing the components of a Vector3 object.

[Flags]
public enum VectorComponent
{
  None = 0,
  X = 1,
  Y = 2,
  Z = 4,
  XY = X | Y,
  XZ = X | Z,
  YZ = Y | Z,
  XYZ = X | Y | Z,
}

Notice I’ve added the entire set of component combinations to the enum values; usually this isn’t feasible and we’d have to rely on runtime behaviour for adding and subtracting flags. In this case however, where the set is small, closed and well known, adding the value permutations is – in my humble opinion at least – the right thing to do.

Where were we? Ah yeah, let’s say we have an instance of said enumeration with the X component set.

var components = VectorComponent.X;

Now, how do I know (at a later date) whether someone’s added another component flag to my simple component value?

public static VectorComponentExtensions
{
  public static bool Contains(this VectorComponent current, VectorComponent value)
  {
    return (current & value) == value;
  }
}

Quick aside again. I’ve opt to use extension methods. I didn’t have to, could have used a static utility class which accepts a normal input value but, I like extension methods for these kind of cases (do try to minimize them though).

And getting back to our enumeration…
Wasn’t that just the cutest little query ever? What else can we do?
Let’s say that now I’ve used the VectorComponent enumeration to lock a particular component of a position value. Like thus:

var locked_components = VectorComponent.Z;

How do I know which components are still free to be manipulated?

public static VectorComponentExtensions
{
  // BUGGY BUGGY BUGGY! DO NOT USE!
  public static VectorComponent GetReversed(this VectorComponent current)
  {
    return current == VectorComponent.None ? VectorComponent.XYZ : ~current;
  }

  // Correct method using the XOR operator.
  public static VectorComponent GetReversed(this VectorComponent current)
  {
    return current^VectorComponent.XYZ;
  }
}

So that’s it for now. Late night. Small snippets of code and the Charlie Daniels Band in my ears. I’ll see you all in the next update. Soonish… honest 😀

“I may be half man, but the other half’s devil, And you’re just exactly like me”