How to write a fancy if statement in one line using lambda?
I want to have something like this:
this.SomeBoolValue == false ? (() => MessageBox.Show("False!")) : (() => MessageBox.Show("True!"));
Thanks
How to write a fancy if statement in one line using lambda?
I want to have something like this:
this.SomeBoolValue == false ? (() => MessageBox.Show("False!")) : (() => MessageBox.Show("True!"));
Thanks
It's really stupid and you should not do that! But for teaching purposes, here's code that does what you want.
(this.SomeBoolValue == false
? (Action)(() => MessageBox.Show("False!"))
: (Action)(() => MessageBox.Show("True!")))();
You need to cast your lambda to some delegate type (here it's Action), because lambda expressions are typeless by default - they are typed according to the context.
You need to actually call the lambda, that's why there is () at the end.
Some 'single line' variants without using lambda that all achieve the same thing:
if(this.SomeBoolValue == false) MessageBox.Show("False!"); else MessageBox.Show("True!");
MessageBox.Show(this.SomeBoolValue ? "True!" : "False!");
MessageBox.Show(string.Format("{0}!", this.SomeBoolValue));