I am wondering if there is any way to declare a byte variable in a short way like floats or doubles? I mean like 5f
and 5d
. Sure I could write
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;
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
...