Wednesday, August 11, 2010

EnumerationExtensions

Here is an extension that helps with bitwise operations on (flagged) enums.

[Flags]
public enum Positions
{
None = 0, Left = 1, Right = 2, Top = 4, Bottom = 8,}

public static class EnumerationExtensions
{ public static T Append<T>(this Enum type, T value)
{ return (T)(object)(((int)(object)type | (int)(object)value)); } public static T Remove<T>(this Enum type, T value)
{ return (T)(object)(((int)(object)type & ~(int)(object)value)); } public static bool Contains<T>(this Enum type, T value)
{ return (((int)(object)type & (int)(object)value) == (int)(object)value); } public static bool ContainsAny<T>(this Enum type, T value)
{ return (((int)(object)type & (int)(object)value) != 0); } public static bool ContainsNot<T>(this Enum type, T value)
{ return !Contains(type, value); } public static bool Is<T>(this Enum type, T value)
{ return (((int)(object)type == (int)(object)value)); } }


then you'll be able to write tests like this :

Positions twoPositions = Positions.Left | Position.Top;
Console.WriteLine(twoPositions.Contains(Position.Top)) // true
Positions position = Positions.None;
position.Append(Position.Bottom);
Console.WriteLine(position.Is(Position.Bottom)); // true (None is overwritten)