I have the following C# code:
byte rule = 0; ... rule = rule | 0x80;
which produces the error:
Cannot implicitly convert type ‘int’ to ‘byte’. An explicit conversion exists (are you missing a cast?)
[Update: first version of the question was wrong … I misread the compiler output]
Adding the cast doesn’t fix the problem:
rule = rule | (byte) 0x80;
I need to write it as:
rule |= 0x80;
Which just seems weird. Why is the |= operator any different to the | operator?
Is there any other way of telling the compiler to treat the constant as a byte?
@ Giovanni Galbo : yes and no. The code is dealing with the programming of the flash memory in an external device, and logically represents a single byte of memory. I could cast it later, but this seemed more obvious. I guess my C heritage is showing through too much!
@ Jonathon Holland : the ‘as’ syntax looks neater but unfortunately doesn’t appear to work … it produces:
The as operator must be used with a reference type or nullable type (‘byte’ is a non-nullable value type)
http://msdn.microsoft.com/en-us/library/kxszd0kx.aspx The | operator is defined for all value types. I think this will produced the intended result. The ‘|=’ operator is an or then assign operator, which is simply shorthand for rule = rule | 0x80.
One of the niftier things about C# is that it lets you do crazy things like abuse value types simply based on their size. An ‘int’ is exactly the same as a byte, except the compiler will throw warnings if you try and use them as both at the same time. Simply sticking with one (in this case, int) works well. If you’re concerned about 64bit readiness, you can specify int32, but all ints are int32s, even running in x64 mode.