c# syntax ((float>0)?(1):(2))


I’m autodidact in c# scripting and I feel more and more enthusiastic about it.
I get oftenly stucked with codes that contains this kind of syntax, which I don’t totally understand. What’s the meaning of the question mark and :frowning: ?

(c# hidden smileys?:slight_smile:

myValue = (anyFloat>0)?(1f)) :(2f));


myValue = (Input.GetKey (KeyCode.Space)? Time.deltaTime: -Time.deltaTime) );

Is it an IF statement or so? What’s the benefit of writing it this way?

Thanks for enlighting me ?:slight_smile:

This is a shortcut for an if:

myValue = anyFloat>0? 1f : 2f;

is the same as:

if (anyFloat > 0){
  myValue = 1F;
} else {
  myValue = 2F;

but is more compact to write, and compiles to a little shorter and faster code:

IL_0001: ldarg.0
IL_0002: ldfld float32 TestIf::anyFloat
IL_0007: ldc.r4 0.0
IL_000c: ble.un IL_001b
IL_0011: ldc.r4 1
IL_0016: br IL_0020
IL_001b: ldc.r4 2
IL_0020: stfld float32 TestIf::myValue

That’s how the if alternative is compiled:

IL_0025: ldarg.0
IL_0026: ldfld float32 TestIf::anyFloat
IL_002b: ldc.r4 0.0
IL_0030: ble.un IL_0045
IL_0035: ldarg.0
IL_0036: ldc.r4 1
IL_003b: stfld float32 TestIf::myValue
IL_0040: br IL_0050
IL_0045: ldarg.0
IL_0046: ldc.r4 2
IL_004b: stfld float32 TestIf::myValue

Your Answer

Stack Overflow is better for none unity questions.