byte is a keyword that is used to declare a variable which can store an unsigned value range from 0 to 255. It is an alias of System. Byte. byte keyword occupies 1 byte (8 bits) in the memory.
You can use a byte literal in Java... sort of. byte f = 0; f = 0xa; 0xa (int literal) gets automatically cast to byte. It's not a real byte literal (see JLS & comments below), but if it quacks like a duck, I call it a duck.
There is no mention of a literal suffix on the MSDN reference for Byte as well as in the C# 4.0 Language Specification. The only literal suffixes in C# are for integer and real numbers as follows:
u = uint
l = long
ul = ulong
f = float
m = decimal
d = double
If you want to use var
, you can always cast the byte as in var y = (byte) 5
Although not really related, in C#7, a new binary prefix was introduced 0b
, which states the number is in binary format. Still there is no suffix to make it a byte though, example:
var b = 0b1010_1011_1100_1101_1110_1111; //int
So, we added binary literals in VB last fall and got similar feedback from early testers. We did decide to add a suffix for byte for VB. We settled on SB (for signed byte) and UB (for unsigned byte). The reason it's not just B and SB is two-fold.
One, the B suffix is ambiguous if you're writing in hexadecimal (what does 0xFFB mean?) and even if we had a solution for that, or another character than 'B' ('Y' was considered, F# uses this) no one could remember whether the default was signed or unsigned - .NET bytes are unsigned by default so it would make sense to pick B and SB but all the other suffixes are signed by default so it would be consistent with other type suffixes to pick B and UB. In the end we went for unambiguous SB and UB. -- Anthony D. Green,
https://roslyn.codeplex.com/discussions/542111
Apparently, it seems that they've done this move in VB.NET (might not be released right now), and they might implement it in roslyn for C# - go give your vote, if you think that's something you'd like. You'd also have a chance to propose a possible syntax.
From this MSDN page, it would seem that your only options are to cast explicitly (var x = (byte)5
), or stop using var
...
As per MSDN you can declare a byte using a decimal, hexadecimal or binary literal.
// decimal literal
byte x = 5;
// hex decimal literal
byte x = 0xC5;
// binary literal
byte x = 0b0000_0101;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With