Search code examples
c#language-construct

How to Subtract Bytes on One Line in C#


This is really odd. Can anyone explain this?

This code does NOT work:

const byte ASC_OFFSET = 96;
string Upright = "firefly";
byte c7 = (byte)Upright[6] - ASC_OFFSET;
//Cannot implicitly convert type 'int' to 'byte'.

This code also does NOT work:

const byte ASC_OFFSET = 96;
string Upright = "firefly";
byte c7 = (byte)Upright[6] - (byte)ASC_OFFSET;
//Cannot implicitly convert type 'int' to 'byte'.

Yet, putting the subtraction on a separate line works just fine:

const byte ASC_OFFSET = 96;
string Upright = "firefly";
byte c7 = (byte)Upright[6];
c7 -= ASC_OFFSET;

I don't mind putting the statements on separate lines, if I have to... but I have to wonder...

Why?


Solution

  • I've noticed this before too. I think it's because the -= operator is predefined for byte types, whereas in the former cases, you're really putting an int inside a byte, which isn't allowed. The reason they did this doesn't necessarily make sense, but it's consistent with the rules, because in the former cases, the compiler can't "peek" at the - operator when doing the assignment.

    If you really need to subtract on one line, instead of saying:

    byte c7 = (byte)Upright[6] - ASC_OFFSET;
    

    Say:

    byte c7 = (byte)(Upright[6] - ASC_OFFSET);