How to Use Lambda That Returns a Value Inline

Why? Because why not.
It also helps understand the language better.



int hour = new Func<int>(() =>
{
    if (int.Parse(comboBoxHour.Text) == 12)
        return comboBoxAmPm.Text == "AM" ? 0 : 12;
    return int.Parse(comboBoxHour.Text) + (comboBoxAmPm.Text == "AM" ? 0 : 12);
})();

Note:
Func is a generic delegate included in the System namespace. It has zero or more input parameters and one out parameter. The last parameter is considered as an out parameter.

Comments