byte op1 = 20;
sbyte op2 = 30;
var result = op1 & op2;
I know that & operator returns bool, but I cunfused now.
why equals result 20? Why is result Int32?
I know that & operator returns bool
That's only true when the operands are bool as well. The &
operator is either logical or bitwise, depending on its operands. From the documentation:
Binary & operators are predefined for the integral types and bool. For integral types, & computes the logical bitwise AND of its operands. For bool operands, & computes the logical AND of its operands; that is, the result is true if and only if both its operands are true.
Perhaps you were thinking of the &&
operator, which is only a logical operator (on any of the predefined types), and which also performs short-circuiting.
As for why the result is int
rather than byte
, sbyte
, short
or ushort
... C# doesn't define arithmetic/bitwise operators for types less than 32 bits. This is discussed in another Stack Overflow question, but it's not specific to &
.
See more on this question at Stackoverflow