Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check if flag contains any value of other flag

I would like compare two flags and see if they have any common value.
I’ld like having an extension method as weel in order to "speed up" coding (I’m going to use it often and on various Enum types). How can I?
This code tell me:

operator ‘&’ cannot be applied to operands of type enum and enum

public enum Tag
{
    Value1 = 1,
    Value2 = 2,
    Value3 = 4,
    Value4 = 8,
    Value5 = 16
}

public static class FlagExt
{
    public static bool HasAny(this Enum me, Enum other)
    {
        return (me & other) != 0;
    }
}

public class Program
{
    public static void Main()
    {
        Tag flag1 = Tag.Value1 | Tag.Value2 | Tag.Value3;
        Tag flag2 = Tag.Value2 | Tag.Value3 | Tag.Value4;
        
        Console.WriteLine(flag1.HasAny(flag2)); // it should returns true. flag1.HasFlag(flag2) returns false.
    }
}

I tried this as well:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    return (((int)me) & ((int)other)) != 0;

but it raises the error:

Cannot convert type ‘System.Enum’ to ‘int’

>Solution :

As per this answer (How to convert from System.Enum to base integer?)

You will need to wrap this code with an exception handler or otherwise ensure that both enums hold an integer.

public static class FlagExt
{
    public static bool HasAny(this Enum me, Enum other)
    {
        return (Convert.ToInt32(me) & Convert.ToInt32(other)) != 0;
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading