Matthias
Matthias

Reputation: 16199

Literal suffix for byte in .NET?

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 inconsistent if you use var for local variables.

Upvotes: 225

Views: 102198

Answers (3)

Matt
Matt

Reputation: 14531

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

Upvotes: 195

Erti-Chris Eelmaa
Erti-Chris Eelmaa

Reputation: 26268

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.

Upvotes: 31

Dan Puzey
Dan Puzey

Reputation: 34200

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

Upvotes: 12

Related Questions