0

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

inside
  • 3,047
  • 10
  • 49
  • 75

2 Answers2

2

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!")))();
  1. 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.

  2. You need to actually call the lambda, that's why there is () at the end.

MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
0

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));
DavidG
  • 113,891
  • 12
  • 217
  • 223