yu yang Jian yu yang Jian - 4 years ago 78
C# Question

Simpler Notation or Way to do If Else in C#

I admire the simplicity of

? : operator
like

bool b;
int x,y,z;

x = b ? y : z;


to replace

if(b)
x = y;
else
x = z;


So I wonder is there some simpler notation or way do
if/else
in more compicated expression , or do something a bit like lambda and I can write more complicated actions in lamda?

For example maybe some imaginary notation like
@ $


to do

x = b @ { z*=3.14; return y; } //if b true do z*=3.14 and x = y
$ { y-= 100; return z; } //if b false do y-=100 and x = z


or

bool b , c
int[] count = new[] {0, 0, 0};

b @ count[0]++ //if b is true do count[0]++
$ c @ count[1]++ //if b is false c is true do count[1]++
$ count[2]++; //if b,c all false do count[2]++


I think the if/else notation is quite brief, however I'll be glad to know if there's a simpler way.

I hope the way can be used under C# 5.0, but in C# 6.0 is welcomed ,too.

Answer Source

You could use a generic extension method with lambdas:

public static T IIf<T>(this bool valueToCheck, Func<T> ifTrue, Func<T> ifFalse)
{
    return valueToCheck ? ifTrue() : ifFalse();
}

And call them like this:

bool flag = ComputeABoolean();
var result = flag.IIf(() => { Console.WriteLine("Yeah this is sort of crazy"); return "Value was true."; },
                      () => { Console.WriteLine("But it does work."); return "value was false";});

This allows complex expressions, side effects, etc.

Personally, I don't think I would ever do this.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download