>>>>>>Any way to do this in C# like VFP's IIF()?
>>>>>>
>>>>>>
>>>>>>if (Checked)
>>>>>>{
>>>>>> _CheckItemsCount++;
>>>>>>}
>>>>>>else
>>>>>>{
>>>>>> _CheckItemsCount--;
>>>>>>}
>>>>>>
>>>>>
>>>>>
_CheckedItemsCount+= (Checked) ? 1:-1;
>>>>
>>>>IMHO, this is harder to read than the original.
>>>
>>>Probably because you're not used to reading it :-}
>>
>>For sure it's in the eyes - and experience - of the beholder.
>>
>>The C/C++/C# conditional operator is so useful I'd bet it's widely implemented in other languages, too. But so is IF... etc.
>>
>>It could be argued that for simple cases like this the *only* significant consideration is readability/maintainability. Any decent optimizing compiler (JIT or otherwise) will probably spit out identical opcode for those two snippets.
>
>I don't think that the first version can be optimized to the same code in this case - it needs to add or subtract based on the condition whilst the second always adds. In fact the code size for the first is 40, for the second 24, FWIW here's the CIL:
.method private hidebysig static void TestA() cil managed
>{
> // Code size 40 (0x28)
> .maxstack 2
> .locals init ([0] bool CS$4$0000)
> IL_0000: nop
> IL_0001: ldsfld bool ConsoleApplication2.Program::Checked
> IL_0006: ldc.i4.0
> IL_0007: ceq
> IL_0009: stloc.0
> IL_000a: ldloc.0
> IL_000b: brtrue.s IL_001b
> IL_000d: ldsfld int32 ConsoleApplication2.Program::_CheckItemsCount
> IL_0012: ldc.i4.1
> IL_0013: add
> IL_0014: stsfld int32 ConsoleApplication2.Program::_CheckItemsCount
> IL_0019: br.s IL_0027
> IL_001b: ldsfld int32 ConsoleApplication2.Program::_CheckItemsCount
> IL_0020: ldc.i4.1
> IL_0021: sub
> IL_0022: stsfld int32 ConsoleApplication2.Program::_CheckItemsCount
> IL_0027: ret
>} // end of method Program::TestA
v
.method private hidebysig static void TestB() cil managed
>{
> // Code size 24 (0x18)
> .maxstack 8
> IL_0000: nop
> IL_0001: ldsfld int32 ConsoleApplication2.Program::_CheckItemsCount
> IL_0006: ldsfld bool ConsoleApplication2.Program::Checked
> IL_000b: brtrue.s IL_0010
> IL_000d: ldc.i4.m1
> IL_000e: br.s IL_0011
> IL_0010: ldc.i4.1
> IL_0011: add
> IL_0012: stsfld int32 ConsoleApplication2.Program::_CheckItemsCount
> IL_0017: ret
>} // end of method Program::TestB
Interesting. I'd have thought an optimizer would deem the two equivalent, but evidently not.
Out of interest, is there any difference using prefix instead of postfix, or a plain old x = x + 1 and x = x - 1 ?
No doubt there are other ways to do this :-\
Regards. Al
"Violence is the last refuge of the incompetent." -- Isaac Asimov
"Never let your sense of morals prevent you from doing what is right." -- Isaac Asimov
Neither a despot, nor a doormat, be
Every app wants to be a database app when it grows up