Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
IIF In C#?
Message
From
18/03/2010 04:59:07
 
 
To
17/03/2010 19:29:45
General information
Forum:
ASP.NET
Category:
Coding, syntax and commands
Title:
Miscellaneous
Thread ID:
01455229
Message ID:
01455300
Views:
56
>>>>>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
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform