简体   繁体   中英

why & operator returns Int32 instead of bool?

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 & .

To my surprise, the other earlier answers missed the interesting part of this question, which sent me scrambling for the C# Language Specification.

Yes, the & operator is defined for a number of different types. And yes, if both arguments are bool then it performs a logical AND operation after evaluating both of its arguments. That is, no shortcircuit. The effect is to call the following function.

bool operator &(bool x, bool y);

But if the arguments are integers it performs a bitwise AND operation after evaluating both arguments and converting them to a common integral type . The effect is to call one of the following overloaded functions.

int operator &(int x, int y);
uint operator &(uint x, uint y);
long operator &(long x, long y);
ulong operator &(ulong x, ulong y);

Note that there is no short or byte versions of these functions, which is why the result in Int32 .

I think this is the real answer to the question.

The & is bitwise operator returns 1 if any one of two bits is 1 and it returns 0 if any of bits is zero. In case of integer or byte like in your problem it perform bitwise operation of AND between two operand so result will be an integer type not boolean. Try using && as it is logical operator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM