Click here to Skip to main content
15,921,884 members
Articles / Programming Languages / C#

Execution Extension Method

Rate me:
Please Sign up or sign in to vote.
5.00/5 (11 votes)
19 Apr 2016CPOL 9.7K   106   9   1
A set of extension methods to support conditional Expression Bodied Functions and Properties


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.


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.


  • 04/19/2016: Initial version
  • 04/21/2016: Article update


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
Software Developer (Senior) Clifford Nelson Consulting
United States United States
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

Comments and Discussions

QuestionMy Vote of 5 Pin
CapGroupAccess24-Oct-18 11:42
CapGroupAccess24-Oct-18 11:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.