Wednesday, September 24, 2008

Returning lambda's from a ternary in C#

In the midst of some mad refactoring I came across something similar to the following snippet:

 1 if (count == 0)
 2   choice.Finish = result => { return; };
 3 else
 4   choice.Finish = result => { letter.MailMerge(result); };

Looked like a decent candidate for refactoring with a ternary / conditional operator:

 7 choice.Finish = (count == 0) ? result => { return; }
 8                              : result => { letter.MailMerge(result); };

Type of conditional expression cannot be determined because there is no implicit conversion between 'lambda expression' and 'lambda expression'

Hold your horses, say what?

For some reason the only way to fool it through the compiler is to cast one of the expressions (it doesn't seem to matter which one) to the expected return type.

11 choice.Finish = (count == 0) ? (TypeDelegate<int>) (result => { return; })
12                              : result => { letter.MailMerge(result); };


Go figure!

No comments: