Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use C#'s ternary operator with two byte values?

Tags:

c#

byte

ternary

There doesn't seem to be a way to use C#'s ternary operator on two bytes like so:

byte someByte = someBoolean ? 0 : 1;

That code currently fails to compile with "Cannot convert source type 'int' to target type 'byte'", because the compiler treats the numbers as integers. Apparently there is no designated suffix to indicate that 0 and 1 are bytes, so the only workarounds are to (a) cast the result into a byte or (b) to use an if-else control after all.

Any thoughts?

like image 819
enderminh Avatar asked Dec 11 '09 19:12

enderminh


People also ask

How is C used?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

How do I start learning C?

To get started with C or C++, you will want a compiler—although nowadays you can also learn C online by experimenting with “hello world” C projects in-browser. Compilers are programs that can be run through command-line interfaces (CLIs).

What is || in C programming?

Logical OR operator: || The logical OR operator ( || ) returns the boolean value true if either or both operands is true and returns false otherwise. The operands are implicitly converted to type bool before evaluation, and the result is of type bool .


2 Answers

byte someByte = someBoolean ? (byte)0 : (byte)1;

The cast is not a problem here, in fact, the IL code should not have a cast at all.

Edit: The IL generated looks like this:

L_0010: ldloc.0          // load the boolean variable to be checked on the stack
L_0011: brtrue.s L_0016  // branch if true to offset 16
L_0013: ldc.i4.1         // when false: load a constant 1
L_0014: br.s L_0017      // goto offset 17
L_0016: ldc.i4.0         // when true: load a constant 0
L_0017: stloc.1          // store the result in the byte variable
like image 174
Lucero Avatar answered Sep 20 '22 19:09

Lucero


You could always do:

var myByte = Convert.ToByte(myBool);

This will yield myByte == 0 for false and myByte == 1 for true.

like image 41
Randolpho Avatar answered Sep 22 '22 19:09

Randolpho