bitwise NOT on const byte fields in C# -


i realized if have field or variable of type 'byte', can apply bitwise not(~) on , cast byte. however, if field 'const byte', can still apply bitwise not(~), cannot cast byte. example,

this compiles:

class program {     byte b = 7;     void method()     {         byte bb = (byte) ~b;     } } 

but has compile error ("constant value '-8' cannot converted 'byte' "):

class program {     const byte b = 7;     void method()     {         byte bb = (byte) ~b;     } } 

i wonder why?

because ~ operator predefined int, uint, long, , ulong. first sample implicitly casts b int, performs negation, explicitly casts byte.

in second example, b constant, compiler inlining negation, making constant int value of -8 (the signed twos-complement of 7). , since constant negative value can't cast byte (without adding unchecked context), compilation error.

to avoid error store result in non-constant int variable:

const byte b = 7;  void main() {     int = ~b;     byte bb = (byte)i; } 

Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

jsf - How to ajax update an item in the footer of a PrimeFaces dataTable? -

django - CSRF verification failed. Request aborted. CSRF cookie not set -