How do you do bitwise & of 2 enums?

Extreme noobie alert! :d How can I get the fallowing code to compile. I am trying to check if a enum contains a value using an & operator like this "this.mintAnchor & AnchorStyles.Right" but I keep getting compile errors regarding cannot convert to bool. Thanks ...

// width
if ((this.mintAnchor & AnchorStyles.Right) & (this.mintAnchor & AnchorStyles.Left))
{
this.Width += WidthDiff;
}
else if (!(this.mintAnchor & AnchorStyles.Left) & !(this.mintAnchor & AnchorStyles.Right))
{
this.Left += WidthDiff;

}
else if (this.mintAnchor & AnchorStyles.Right)
{
this.Left += WidthDiff;
}

// height
if ((this.mintAnchor & AnchorStyles.Bottom) && (this.mintAnchor & AnchorStyles.Top))
{
this.Height += HeightDiff;

}
else if (!(this.mintAnchor & AnchorStyles.Top) && !(this.mintAnchor & AnchorStyles.Bottom))
{
this.Top += HeightDiff;

}
else if (this.mintAnchor & AnchorStyles.Bottom)
{
this.Top += HeightDiff;

}



Answer this question

How do you do bitwise & of 2 enums?

  • helsingfors

    Seems like a lot of writing just for a boolean test.... is there any way to simplify your code using << >> operators, something like...

    ESample test = ESample.one | ESample.two;
    if (test << ESample.one) {
    Console.WriteLine("it works");
    }



    ... i'm kind of a die hard vb.net developer so I only have used C# when converting C# code over to vb.net. But lately I have been writing actual C# code in C# express and XNA and it's going pretty good, certainly having an easier time then what I was expecting to, but every now and then I run into a situation where I am not sure how to do it in C#. Thanks for your help!

  • Rod Blackwood

    Write it like this:

    [Flags]
    private enum ESample {
    one = 1,
    two = 2,
    three = 4
    }
    private void EnumTest() {
    ESample test = ESample.one | ESample.two;
    if ((test & ESample.one) == ESample.one && (test & ESample.two) == ESample.two) {
    Console.WriteLine("it works");
    }
    }



  • How do you do bitwise & of 2 enums?