In this tutorial we you will learn delegates using easy to follow step by step examples.
Example 1: NumberChanger Example using Delegates
This is a simple numberchanger example using C# delegates.
Step 1: Create the Delegate
Start by creating a delegate method like this using the delegate
keyword:
delegate int NumberChanger(int n);
Step 2: Full Code
Now create a class to utilize that delegate. Here is the full code
using System;
delegate int NumberChanger(int n);
class Delegate
{
static int num = 10;
public static int sum(int num1)
{
num = num + num1;
return num;
}
public static int mul(int num1)
{
num = num * num1;
return num;
}
static void Main(string[] args)
{
NumberChanger addition = new NumberChanger(sum);
Console.WriteLine(addition(5));
NumberChanger multiply = new NumberChanger(mul);
Console.WriteLine(multiply(20));
}
}
Run
Run the project and you will get the following:
15
300