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

后端 未结 4 1656
悲&欢浪女
悲&欢浪女 2020-12-18 00:50

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 currentl

4条回答
  •  囚心锁ツ
    2020-12-18 01:21

    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
    

提交回复
热议问题