Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if an enum has any flags in common [duplicate]

Consider I have this extension method:

public static bool HasAnyFlagInCommon(this System.Enum type, Enum value)
{
    var flags = value.ToString().Split(new string[] { ", " }, 
                                    StringSplitOptions.None);
    foreach (var flag in flags)
    {
        if (type.ToString() == flag)
            return true;
    }
    return false;
}

And the following situation:

[Flags]
enum Bla
{
    A = 0,
    B = 1,
    C = 2,
    D = 4
}

Bla foo = Bla.A | Bla.B;
Bla bar = Bla.A;

bar.HasAnyFlagInCommon(foo); //returns true

I want to check if foo has any flags in common with bar, but there got to be a better way of achiving this behavior in the extension method.

I also tried like this, but is always returns true:

    public static bool HasAnyFlagInCommon(this System.Enum type, Enum value)
    {
        var flags = Enum.GetValues(value.GetType()).Cast<Enum>()
                                 .Where(item => value.HasFlag(item));
        foreach (var flag in flags)
        {
            if (type == flag)
                return true;
        }
        return false;
    }
like image 615
Erpel Avatar asked Dec 13 '12 18:12

Erpel


1 Answers

You can simply cast the Enum value to a ulong (to account for the possibility that the underlying type is not the default of int). If the result != 0, at least one flag was set.

ulong theValue = (ulong)value;
return (theValue != 0);

Remember, at the end of the day, the enum is backed by one of byte, sbyte, short, ushort, int, uint, long, or ulong.

http://msdn.microsoft.com/en-us/library/sbbt4032.aspx

A flag being set is the same as a corresponding bit being turned on in the backing type. The ulong above will only be 0 if all bits are turned off.

UPDATE

The question was edited after this answer was posted, so here's a modification to account for that update:

To then see whether the enum has any flags in common with another instance of that enum, you can use bitwise and. If both have any common bit position set, the result will be non-zero:

var anyFlagsInCommon = ((ulong)value) & ((ulong)compareTo);
like image 99
Eric J. Avatar answered Oct 20 '22 07:10

Eric J.