Wednesday, February 10, 2010

C# Flags Enumeration Helper

Working in the confines of .NET 2.0 (no extension methods), I was in dire need of a helper that would assist in the checking and manipulating of flags enumerations. Over the years that I have used them, I've been bitten enough times using the wrong operators and having to deal with other people maintaining my code that used these enumerations that I finally wrote an enum helper.

This helper covers the setting, checking, and evaluating the flags that have been set on the enum. I wanted to share it with y'all to save you a little of the grief that I have borne. Here it is:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace TestFlags
{
class Program
{
[Flags]
public enum Flags
{
None = 0,
First = 1,
Second = 2,
Third = 4
}
static void Main(string[] args)
{
var flag = Flags.None;

Debug.Assert(Enum.EnumHasFlag(flag, Flags.Second));
Debug.Assert(Enum.EnumHasFlag(flag, Flags.Third));

List allFlags = Enum.GetFlagEnumList(flag);
foreach (var allFlag in allFlags)
{
Console.WriteLine(allFlag);
}

Console.ReadKey();
}
}

///
/// Assists with enum operations
///
/// The type of the enum.
public static class Enum where TEnum : struct
{
///
/// Adds the specified flag to an enum.
///
/// The append to.
/// To append.
public static void AddFlagToEnum(ref TEnum appendTo, TEnum toAppend)
{
int appendToInt = Convert.ToInt32(appendTo);
int toAppendInt = Convert.ToInt32(toAppend);

appendTo = (TEnum)(object)(toAppendInt | appendToInt);
}

///
/// Determines whether the enum has a certain flag
///
/// The flags enum value to check to see if it contains the checkAgainst value.
/// The flags enum value to check against.
/// whether the enum contains a certain flag
public static bool EnumHasFlag(TEnum toCheck, TEnum checkAgainst)
{
int checkAgainstInt = Convert.ToInt32(checkAgainst);
int toCheckInt = Convert.ToInt32(toCheck);
return (checkAgainstInt & toCheckInt) == checkAgainstInt;
}

///
/// Gets the flag enum list.
///
/// The flags.
/// The list of enum values contained in the flag
public static List GetFlagEnumList(TEnum flags)
{
List result = new List();
var enumValues = (TEnum[])Enum.GetValues(typeof(TEnum));
foreach (var enumValue in enumValues)
{
if (Convert.ToInt32(enumValue) != 0 && EnumHasFlag(flags, enumValue))
{
result.Add(enumValue);
}
}
return result;
}
}
}

No comments: