On 11/7/2011 10:11 AM, Marcel Müller wrote:
> On 07.11.2011 11:51, The Last Danish Pastry wrote:
>> void Test(byte x, byte y)
>> {
>> byte z = x& y;
>> }
>>
>> This gives an error: "Cannot implicitly convert type 'int' to 'byte'. An
>> explicit conversion exists (are you missing a cast?)"
>>
>> But, in "& Operator (C# Reference)" we read...
>>
>> Binary& operators are predefined for the integral types and bool.
>>
>> In "Integral Types Table (C# Reference)" we see that byte is an "integral
>> type".
>>
>> What is going on? Programmers have been anding together two bytes to get
>> another byte for decades.
>
> Probably C# invokes the & operator with implicit propagation to int (as
> well as C does). So the result of x&y is of type int rather than byte
> (or short). So you have to write
> byte z = (byte)(x & y);
>
> The same applies to binary operator +, where the result will not
> necessarily fit into a byte.
Exactly.
The issue is the same in Java (and Java also requires an
explicit cast).
Arne
|