tags:

views:

1110

answers:

6

In C and C++ you can tell the compiler that a number is a 'long' by putting an 'l' at the end of the number. e.g long x = 0l;

How can I tell the C# compiler that a number is a byte?

+3  A: 
byte b = (byte) 123;

even though

byte b = 123;

does the same thing. If you have a variable:

int a = 42;
byte b = (byte) a;
Sklivvz
+2  A: 

Remember, if you do:

byte b = (byte)300;

it's not going to work the way you expect.

casademora
A: 

MSDN uses implicit conversion. I don't see a byte type suffix, but you might use an explicit cast. I'd just use a 2-digit hexadecimal integer (int) constant.

aib
A: 

No need to tell the compiler. You can assign any valid value to the byte variable and the compiler is just fine with it: there's no suffix for byte.

If you want to store a byte in an object you have to cast:

object someValue = (byte) 123;
VVS
+3  A: 

According to the C# language specification there is no way to specify a byte literal. You'll have to cast down to byte in order to get a byte. Your best bet is probably to specify in hex and cast down, like this:

byte b = (byte) 0x10;
Douglas Mayle
A: 

See also the question: C# numeric constants

Rob Walker