Introduction
Expression Bodied Functions and Properties are a feature of C# 6.0. The limitation of this technology is that there can be only a single statement, and even a simple if
statement is still multiline.
Code
Here are the three extension methods I have created to execute a line of code:
public static void ExecuteIfTrue(this bool value, Action action)
{
if (value) action();
}
public static void ExecuteIfFalse(this bool value, Action action)
{
if (!value) action();
}
public static void Execute(this bool value, Action actionTrue, Action actionFalse = null)
{
if (value) actionTrue();
else actionFalse?.Invoke();
}
Using the Code
Here is a simple example of using one of these extension methods in a property:
private void DisplayMessageBox() => Flag.ExecuteIfTrue(
() => MessageBox.Show("The Flag is set to true"));
Another example using true and false lambda expressions:
public void Execute(object parameter) =>
(parameter != null).Execute(() => _action(parameter),() =>_action("-1") );
The Sample
The sample is a very simple program that only shows a MessageBox
when the Button
is clicked if the CheckBox
is checked.
![](1094521/ExecuteIfTrueSample--False.png)
![](1094521/ExecuteIfTrueSample--True.png)
The extension methods are used in the ViewModel
for the ICommand
for the button, and in the RelayCommand
class.
History
- 04/19/2016: Initial version
- 04/21/2016: Article update