It’s possible to write code for years without deliberately using delegate
, Action
, or Func
types. I say “deliberately” because we may have used them without realizing it.
Knowing what these types represent makes reading code easier. Knowing how to use them adds some useful tools to our developer toolbox.
What Is a `delegate`?
A delegate
is a type that represents a method with a specific signature and return type.
The declaration of a delegate looks exactly like the declaration of a method, except with the keyword delegate
in front of it.
Examples:
- A delegate representing a method that adds two numbers and returns a result:
delegate int AddNumbers(int value1, int value2);
- A delegate representing a method that logs an exception and doesn’t return anything:
delegate void LogException(Exception ex);
- A delegate representing a function that converts some generic type to a
string
:delegate string FormatAsString<T>(T input);
Just like classes and interfaces, we can declare delegates outside of classes or nested within classes. We can mark them private
, public
, or internal
.
public delegate int MyDelegate(int x, int y);
class Program
{
static int Sum(int x, int y)
{
return x + y;
}
static void Main()
{
MyDelegate d = new MyDelegate(Sum);
int result = d.Invoke(12, 15);
// or your can use d(12,15);
Console.WriteLine(result);
Console.ReadLine();
}
}
Multicast Delegate
public class Program
{
public delegate void delmethod();
public static void method()
{
Console.WriteLine("Method 1");
}
public static void method2()
{
Console.WriteLine("Method 2");
}
public static void Main(string[] args)
{
delmethod del = null;
del += method;
del += method2;
del.Invoke();
}
}
Action, Func, and Predicate delegates in C#
Func is a delegate that points to a method that accepts one or more arguments and returns a value.
Action is a delegate that points to a method which in turn accepts one or more arguments but returns no value. In other words, you should use Action when your delegate points to a method that returns void.
A Predicate is a delegate that accepts one or more generic parameters and returns a Boolean value — you can assume it is something like Func<T,bool>. Predicate delegates are typically used to perform search operations on some data based on a set of criteria.
Programming Action delegates in C#
You can take advantage of delegates in C# to implement events and call back methods. A delegate in C# is similar to function pointers of C++, but C# delegates are type safe. You can pass methods as parameters to a delegate to allow the delegate to point to the method.
The following code snippet illustrates the syntax for using Action delegate.
Action<TParameter>
The following code listing shows how you can use Action delegate. This code snippet when executed would print the word “Hello!!!” in the console window.
static void Main(string[] args)
{
Action<string> action = new Action<string>(Display);
action("Hello!!!");
Console.Read();
}
static void Display(string message)
{
Console.WriteLine(message);
}
Programming Func delegates in C#
Let’s now understand how we can work with Func delegates in C#. Here is the syntax for a Func delegate.
Func<TParameter, TOutput>
The following code snippet illustrates how you can use a Func delegate in C#. It prints the value of Hra (calculated as 40% of basic salary). The basic salary is passed to it as an argument.
static void Main(string[] args)
{
Func<int, double> func = new Func<int, double>(CalculateHra);
Console.WriteLine(func(50000));
Console.Read();
}
static double CalculateHra(int basic)
{
return (double)(basic * .4);
}
Programming Predicate delegates in C#
A Predicate delegate is typically used to search items in a collection or a set of data. Here is the syntax for a Predicate delegate. It Uses only one type argument.
Predicate<T>
Note that Predicate<T> is basically equivalent to Func<T,bool>.
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
Predicate<int> predicate = new Predicate<int>(IsAbove5);
Console.WriteLine(predicate.Invoke(2));
}
static bool IsAbove5(int x)
{
return x>5;
}
Using function as a parameter in a delegate
public delegate void delegatewithdelgateparameter(print str);
public delegate void printdelegate(string str);
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
printdelegate del;
del = Print2;
del += Print3;
delegatewithdelgateparameter printm = Print1;
printm.Invoke(del);
}
static void Print1(print str)
{
str("Hello ");
}
static void Print2(string str)
{
Console.WriteLine("Hello2 " +str);
}
static void Print3(string str)
{
Console.WriteLine("Hello3 "+str);
}