6

Can someone explain why is this not valid? I get "can't convert to int to bool"

 if (b & 1)

also, why can't I do

 b & 1 

in code, is this the correct way of doing this?

 int b = b & 1
 if(b)

Thanks!

1 Answer 1

13

It's because the result of b & 1 is an integer (if b is an integer).

A correct way to do this is (among others):

if ((b & 1) != 0) { ... }

or

if (Convert.ToBoolean(b & 1)) { ... }

Sign up to request clarification or add additional context in comments.

5 Comments

Note that your third example will also fail for this reason. You'd have to convert "b" to an integer or compare it with 0, since if can only compare boolean expressions.
so if I want to do a regular bit operation like this somewhere in the code (b&8) like I would in javascript, c# I would have to write b = b & 2; correct?
No, you don't need to store the result in a variable (seem my first example); you just need to understand that the result will be strongly-typed as an integer, and that you will have to convert it or compare it to another integer. Note that C# doesn't consider 0 to be "false" like C or JS does. In my first example, I'm literally comparing the integer output of b & 1 to the number 0.
when if(b & 1) gets executed, does the b value get updated and will differ after if stamement or it works the same way as if(a-1>3) where a stays the same after the if statement, not like a = a -1; if that makes sense
In both of your examples, both "a" and "b" never change. As I said, just the expression if (b & 1) is illegal, since b & 1 is not a boolean expression, so your question doesn't really make any sense... The expression if(b & 1) is equivalent to c = b & 1; if (c).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.