Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Execution Extension Method

0.00/5 (No votes)
19 Apr 2016 1  
A set of extension methods to support conditional Expression Bodied Functions and Properties

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

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here