C# / C# Delegates, Events, and Lambdas

Using Action, Func, and Predicate Delegates

Action, Func, and Predicate are built-in delegates in C# that can encapsulate methods. This tutorial will introduce you to these delegates and show you how to use them in your C# …

Tutorial 5 of 5 5 resources in this section

Section overview

5 resources

Covers delegates, events, and lambda expressions for advanced programming in C#.

Tutorial: Using Action, Func, and Predicate Delegates in C

1. Introduction

Tutorial's Goal

This tutorial aims to provide a comprehensive guide on using Action, Func, and Predicate Delegates in C#. These delegates represent methods with different signatures and usage that can make your code more flexible and generic.

What You Will Learn

By the end of this tutorial, you will understand the following concepts:
- What are Action, Func, and Predicate delegates
- How to use these delegates in your C# programs

Prerequisites

Before getting started, you should have a basic understanding of C# programming and its syntax.

2. Step-by-Step Guide

Action Delegates:

The Action delegate in C# represents a method that contains a void return type and optionally has parameters.

Example:

// Define an Action delegate
Action<string> display = delegate(string message)
{
    Console.WriteLine(message);
};

// Use the delegate
display("Hello, World!");

Func Delegates:

Func delegate represents a function that can take up to 16 input parameters and returns a value. The last type parameter is always the result.

Example:

// Define a Func delegate
Func<int, int, int> add = delegate(int a, int b)
{
    return a + b;
};

// Use the delegate
int result = add(10, 20);
Console.WriteLine(result); // Outputs 30

Predicate Delegates:

Predicate delegate represents a method that takes one input parameter and returns a boolean value.

Example:

// Define a Predicate delegate
Predicate<string> isUpper = IsUpperCase;

bool result = isUpper("hello");
Console.WriteLine(result); // Outputs False

public static bool IsUpperCase(string str)
{
    return str.Equals(str.ToUpper());
}

3. Code Examples

Let's take a look at some more detailed examples:

Using Action Delegate

Action<int, int> calculate = (a, b) =>
{
    Console.WriteLine($"Sum: {a + b}");
    Console.WriteLine($"Difference: {a - b}");
};

calculate(10, 5); 
// Outputs: 
// Sum: 15
// Difference: 5

Using Func Delegate

Func<int, int, int> multiply = (a, b) => a * b;
int product = multiply(10, 2);
Console.WriteLine($"Product: {product}"); // Outputs: Product: 20

Using Predicate Delegate

Predicate<int> isEven = n => n % 2 == 0;
bool result = isEven(4);
Console.WriteLine($"Is Even: {result}"); // Outputs: Is Even: True

4. Summary

In this tutorial, we covered:

  • Action, Func, and Predicate delegates in C#
  • How to define and use these delegates
  • Examples of these delegates in action

Next, you can explore more about delegates and their use cases in C#. For more information, refer to the Microsoft C# Delegates Documentation.

5. Practice Exercises

  1. Write a method using Func delegate that takes two strings and returns their concatenation.
  2. Write a method using Predicate delegate that checks if a number is a prime number.
  3. Write a method using Action delegate that prints square of a number.

Solutions

Func<string, string, string> concatenate = (a, b) => a + b;
string result = concatenate("Hello, ", "World!");
Console.WriteLine(result); // Outputs: Hello, World!
Predicate<int> isPrime = n =>
{
    if (n <= 1) return false;
    for (int i = 2; i * i <= n; i++)
    {
        if (n % i == 0) return false;
    }
    return true;
};
bool result = isPrime(7);
Console.WriteLine(result); // Outputs: True
Action<int> printSquare = n => Console.WriteLine(n * n);
printSquare(5); // Outputs: 25

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Text Diff Checker

Compare two pieces of text to find differences.

Use tool

Image Converter

Convert between different image formats.

Use tool

JSON Formatter & Validator

Beautify, minify, and validate JSON data.

Use tool

Random Name Generator

Generate realistic names with customizable options.

Use tool

Timestamp Converter

Convert timestamps to human-readable dates.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help