tags:

views:

176

answers:

5

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);
+12  A: 

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
Darin Dimitrov
Thanks, I didn't know the term suffix, had I known it Fredrik's link to the other SO post would have come up #1
Nathan Koop
+1  A: 

Hex notation:

Byte b = 0xff;

Jeff Meatball Yang
Could also be interpredet as a signed byte.
Daniel Brückner
How different is 0xff from 255?
Serge - appTranslator
SByte foo = 0xFF; // Sets foo to -1.
Daniel Brückner
Byte foo = 0xFF; // Sets foo to +255.
Daniel Brückner
+2  A: 

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;
Daniel Brückner
There's really no need for a cast here...
Arjan Einbu
Not really necessary as long as the value is less than 256, unless you type 'var' to use type inference.
Cecil Has a Name
@Arjan, in my situation it's: byte myByte = a==b?1:0; and I need a cast.
Nathan Koop
I wouldn't use one here - but I could imagine situations where you could give hints to the compiler or run time that the result is wrong by an explicit cast. Very artificial example and not realy releated to the question. int foo = (Byte) Bar(); where Bar() returns an integer but you exspect the result to be in the byte range.
Daniel Brückner
The conditional operator is a very good example - the compiler is not very good at infering the type.
Daniel Brückner
+2  A: 

According to this post, byte has no such suffix.

Fredrik Mörk
+2  A: 

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

Jeff Fritz