top of page
Writer's pictureThe Tech Platform

C# Delegates: Func Delegate, Action Delegate and Predicate Delegate

A delegate is an object which refers to a method or you can say it is a reference type variable that can hold a reference to the methods. Delegates in C# are similar to the function pointer in C/C++. It provides a way which tells which method is to be called when an event is triggered.


For example, if you click on a Button on a form (Windows Form application), the program would call a specific method. In simple words, it is a type that represents references to methods with a particular parameter list and return type and then calls the method in a program for execution when it is needed.

There are three steps involved while working with delegates:

  1. Declare a delegate

  2. Set a target method

  3. Invoke a delegate


Important Points:

  • Provides a good way to encapsulate the methods.

  • Delegates are the library class in System namespace.

  • These are the type-safe pointer of any method.

  • Delegates are mainly used in implementing the call-back methods and events.

  • Delegates can be chained together as two or more methods can be called on a single event.

  • It doesn’t care about the class of the object that it references.

  • Delegates can also be used in “anonymous methods” invocation.

  • Anonymous Methods(C# 2.0) and Lambda expressions(C# 3.0) are compiled to delegate types in certain contexts. Sometimes, these features together are known as anonymous functions.


Syntax:

A delegate can be declared using the delegate keyword followed by a function signature, as shown below.

[access modifier] delegate [return type] [delegate name]([parameters])

Types of Delegates:

There are three types of Delegates in C#:

  1. Func Delegate

  2. Action Delegate

  3. Predicate Delegate


Func Delegates

Func is a generic delegate included in the System namespace. It has zero or more input parameters and one out parameter. The last parameter is considered as an out parameter.


The Func delegate that takes one input parameter and one out parameter is defined in the System namespace, as shown below:

namespace System 
{         
    public delegate TResult Func<in T, out TResult>(T arg); 
} 

The last parameter in the angle brackets <> is considered the return type, and the remaining parameters are considered input parameter types, as shown in the following figure.



A Func delegate with two input parameters and one out parameters will be represented as shown below.




The following Func delegate takes two input parameters of int type and returns a value of int type:

Func<int, int, int> sum; 

You can assign any method to the above func delegate that takes two int parameters and returns an int value.

class Program 
{     
    static int Sum(int x, int y)     
    {         
        return x + y;     
    }      
    
    static void Main(string[] args)     
    {         
        Func<int,int, int> add = Sum;          
        int result = add(20, 50);          
        Console.WriteLine(result);      
    } 
}

Output:



Action Delegates

Action is a delegate type defined in the System namespace. An Action type delegate is the same as Func delegate except that the Action delegate doesn't return a value. In other words, an Action delegate can be used with a method that has a void return type.


For example, the following delegate prints an int value.

public delegate void Print(int val); 
 
static void ConsolePrint(int i) 
{     
    Console.WriteLine(i); 
}  

static void Main(string[] args) 
{                
    Print prnt = ConsolePrint;     
    prnt(10); 
}


Predicate Delegates

Predicate is the delegate like Func and Action delegates. It represents a method containing a set of criteria and checks whether the passed parameter meets those criteria. A predicate delegate methods must take one input parameter and return a boolean - true or false.


The Predicate delegate is defined in the System namespace, as shown below:

public delegate bool Predicate<in T>(T obj);

Same as other delegate types, Predicate can also be used with any method, anonymous method, or lambda expression.


using System;

public class Program
{
	public static void Main()
	{
		Predicate<string> isUpper = IsUpperCase;

		bool result = isUpper("hello world!!");
	
		Console.WriteLine(result);
	}
	
	public static bool IsUpperCase(string str)
	{
		return str.Equals(str.ToUpper());
	}

}

Output:



Resource: TutorialsPoint, Tutorialteacher


The Tech Platform

0 comments

Recent Posts

See All

Комментарии


bottom of page