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.


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
Has been working as a C# developer on contract for the last several years, including 3 years at Microsoft. Previously worked with Visual Basic and Microsoft Access VBA, and have developed code for Word, Excel and Outlook. Started working with WPF in 2007 when part of the Microsoft WPF team. For the last eight years has been working primarily as a senior WPF/C# and Silverlight/C# developer. Currently working as WPF developer with BioNano Genomics in San Diego, CA redesigning their UI for their camera system. he can be reached at qck1@hotmail.com.