How to work with Action, Func, and Predicate delegates in C#


While passing objects as arguments is a standard and familiar way to invoke methods, providing methods as arguments to other methods is less so. Nonetheless, we often must pass a method as a parameter to another method when working with event handling in C#. We do this using delegates.

I provided an overview of delegates in an earlier article here. In this article, we’ll examine how we can work with Action, Func, and Predicate delegates in C#. To work with the code examples provided in this article, you should have Visual Studio 2022 installed in your system. If you don’t already have a copy, you can download Visual Studio 2022 here.

A delegate is a type-safe function pointer that can reference a method that has the same signature as that of the delegate. Delegates are used to define callback methods and implement event handling, and they are declared using the “delegate” keyword. You can declare a delegate that can appear on its own or even nested inside a class.

What are Func and Action delegates? How can they be used?

The most common delegates in C# are the Func delegate and the Action delegate. Both are reference types that encapsulate a method. The Func delegate points to a method that accepts parameters and returns a value; the Action delegate points to a method that accepts parameters but does not return a value (i.e., returns void).

Both of these delegate objects will take zero or many parameters, and we can use them with lambda expressions or anonymous methods.

The syntax for creating an action delegate in C# is

Copyright © 2023 IDG Communications, Inc.


Source : https://www.infoworld.com/article/3057152/how-to-work-with-action-func-and-predicate-delegates-in-c-sharp.html#tk.rss_all

Leave a Comment

SMM Panel PDF Kitap indir