Question

I know that I can assign a value specifically to a float by doing

float y = 4.5f;

I want to do the same thing, except as a byte. How do I do this? I've checked the MSDN documentation and cannot find anything related to this. Also, what is this called?

Thanks,

[Edit]

For clarity the code I'm using this on is

byte myByte = a==b?1:0;

and the error I get is

Cannot implicitly convert type 'int' to 'byte?'. An explicit conversion exists (are you missing a cast?)

Solution

byte myByte = (byte)(a==b?1:0);
Was it helpful?

Solution

The byte, sbyte, short and ushort data types do not have designated suffixes. However, integer literal can be assigned to variables of these data types and will be implicitly converted, assuming that the value is appropriate for storage in the variable. Just for the record here are the defined literals in C#:

uint: U or u
long: L or l
ulong: UL or ul
float: F or f
decimal: M or m

OTHER TIPS

I would just use a cast.

// Okay
Byte data = (Byte) 57;

// Error (but I don't know if it is a compiler error or a runtime error)
Byte data = (Byte) -17;

Or introduce a constant.

// Okay
const Byte foo = 57;
Byte data = foo;

// Compiler Error
const Byte foo = -17;
Byte data = foo;

According to this post, byte has no such suffix.

You don't need a suffix when defining a byte:

   byte b = 1;

You just need to ensure that your value is between 0 and 255.

MSDN refers to the use of the F as a 'suffix', forcing a Literal Type.

See the following article at C-sharp Online for more information

Hex notation:

Byte b = 0xff;

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top