Literal suffix for byte in .NET?

C#.NetValue Type

C# Problem Overview


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 byte x = 5, but that's a bit inconsequential if you use var for local variables.

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

> 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.

Solution 3 - C#

From this MSDN page, it would seem that your only options are to cast explicitly (var x = (byte)5), or stop using var...

Solution 4 - C#

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;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMatthiasView Question on Stackoverflow
Solution 1 - C#MattView Answer on Stackoverflow
Solution 2 - C#Erti-Chris EelmaaView Answer on Stackoverflow
Solution 3 - C#Dan PuzeyView Answer on Stackoverflow
Solution 4 - C#Adrian TomanView Answer on Stackoverflow