C# Delegates
Before learning a new subject, I often ask myself some questions to improve my learning process. So, let’s start questioning together??
What does C# delegate mean?
Reference types let us manipulate objects by using small references instead of writing the whole object every time we need. For instance, “String”, “Arrays” and “Classes” are reference type data types. A delegate is also a reference type that holds the memory address of a method.
(A method is a block of code which might take parameters and might return a value and performs actions.)
When can I use C# delegates?
When you need to call a series of methods, you can use a single delegate to call a series of methods, or you can call two methods the same in signature using delegate. Another use of delegate is that you can pass methods as arguments to other methods.
How to Declare a delegate?
// MyCustomDelegate does not return any value
public delegate void MyCustomDelegate();
// MyCustomDelegate2 returns an integer
private delegate int MyCustomDelegate2(string newString);
I created a method and a delegate to calculate the sum of two numbers in the code below:
领英推荐
class Progra
{
//This delegate returns nothing but takes two parameters.
public delegate void ThisDelegateAddTwoNumbers(int firstNumber, int secondNumber);
// Main method
static void Main(string[] args)
{
//Set target method
ThisDelegateAddTwoNumbers additionDelegate = Addition;
//There are two ways to invoke a delegate.
additionDelegate(9, 9);
// addition.Invoke(9,9)
}
// This method adds two numbers and returns nothing but prints the result.
public static void Addition(int firstNumber, int secondNumber)
{
Console.WriteLine($"{firstNumber} + {secondNumber}: {firstNumber + secondNumber}");
}
}
Like other reference types and primitive types, we can pass delegate as a parameter. We can also set new targets using +=(-=) just like we do when we concatenate multiple strings using +=(-=). Let’s analyze delegates together in the code below!
class Progra
{
// Main method
static void Main(string[] args)
{
ThisIsADelegate firstDelegate = ThisMethodReturnsAString;// Set a target
ThisIsADelegate secondDelegate = ThisMethodAlsoReturnsAString;// Set a target
// Output: 1.Hello 2.World
string concatTwoStringsByCallingDelegates = firstDelegate("Hello") + " " + secondDelegate.Invoke("World");
Console.WriteLine(concatTwoStringsByCallingDelegates);
// The last assigned target method's value will be returned
ThisIsADelegate tryToConcatTwoStrings = firstDelegate;
tryToConcatTwoStrings += secondDelegate;
// Output: 2.Hello
Console.WriteLine(tryToConcatTwoStrings.Invoke("Hello"));
}
// This delegate returns a string and takes a string as a parameter.
public delegate string ThisIsADelegate(string message);
// This method returns given string.
public static string ThisMethodReturnsAString(string message)
{
return "1." + message;
}
// This method also returns given string.
public static string ThisMethodAlsoReturnsAString(string message)
{
return "2." + message;
}
}
Func Delegate and Action
Did it bother you to define delegates manually every time? Now, it’s time to learn c# Func delegate that saves us from repetitive manual works. Func is a genereic delegate.
Func<input_parameter,output_parameter>
Func<int,int> //---> output_parameter: int
Func<string,int,bool> //---> output_parameter: boolean
If a delegate does not return any value, you can use action instead of Func.
action<int> // ---> input_parameter: int
Let’s write the same code using Func:)
class Program
{
// Main method
static void Main(string[] args)
{
// Outout: 1.Hello
Func<string, string> firstDelegate = ThisMethodReturnsAString;// set a target
Console.WriteLine(firstDelegate("Hello"));
// Outout: 2.Hello
firstDelegate += ThisMethodAlsoReturnsAString;
Console.WriteLine(firstDelegate("Hello"));
}
// This method returns given string.
public static string ThisMethodReturnsAString(string message)
{
return "1." + message;
}
// This method also returns given string.
public static string ThisMethodAlsoReturnsAString(string message)
{
return "2." + message;
}
}