8

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?

1
  • I like the answers, but is casting the number to a byte the same as declaring the number as a byte? Commented Sep 30, 2008 at 14:30

5 Answers 5

10
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; 
Sign up to request clarification or add additional context in comments.

1 Comment

integer literal will be implicitly converted from int to byte so you don't need to put (byte) cast before number. In case some one has missed the logic for above example.
8

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; 

1 Comment

Is (byte) casting a "no-op" ? Or is true that at least some time required?
3

Remember, if you do:

byte b = (byte)300; 

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

3 Comments

The truth of that statement depends on my expectations ;-)
@casademora elaborate on that, like what's the result gonna be?
A byte can only store numbers from 0 to 255 (1111 1111 = 255). This number can't be stored in one byte, so it will be "truncated" to one byte.
1

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.

Comments

1

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; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.