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

本小妞迷上赌 提交于 2019-11-28 00:20:33

问题


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?


回答1:


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



回答2:


You could always do:

var myByte = Convert.ToByte(myBool);

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




回答3:


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



回答4:


That compiles OK on VS2008.

Correction: This compiles OK in VS2008:

byte someByte = true ? 0 : 1;
byte someByte = false ? 0 : 1;

But this does not:

bool someBool = true;
byte someByte = someBool ? 0 : 1;

Odd!

Edit: Following Eric's advice (see his comment below), I tried this:

const bool someBool = true;
byte someByte = someBool ? 0 : 1;

And it compiles perfectly. Not that I distrust Eric; I just wanted to include this here for the sake of completeness.



来源:https://stackoverflow.com/questions/1890390/how-to-use-cs-ternary-operator-with-two-byte-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!