USING DELEGATES IN C#
What Will I Learn?
Write here briefly the details of what the user is going to learn in a bullet list.
- Delegates
Requirements
- Visual Studio 2015
Difficulty
- Intermediate
Tutorial Contents
Basic Theory
Delegates are used to make callbacks and to do other tasks in C#. They are used to pass methods around. If you’re an experienced programmer, you will notice that delegates and function pointers of c/c++ are similar to each other. They are used to reference a method and can be derived implicitly using the “System.Delegate Class.” You can declare a delegate using the “delegate” keyword using the template below:
delegate < delegate name>()
**Creating our first Delegate:
**
public delegate void PointToVoidMethod(int a, int b);
This delegate encapsulates any method that takes two integers as parameters and return with a void.
Then we create two void methods to add two numbers and to find the square of two number.
public void addNumber(int a, int b)
{
Console. WriteLine($"The Value is {a+b}");
}
public void FindSquareOfNumber( int s, int p )
{
Console. WriteLine($"The square is {Math.Pow(s, p)}");
}
You can see that both methods have the same signature as the delegate (i.e. two integer parameters and a void return type), so it can be used with our delegate.
Now write the following code in your main method:
static int Main(string[] args)
{
FirstLessonDelegates frst = new FirstLessonDelegates();
PointToVoidMethof ptm = new PointToVoidMethof(frst.addNumber);
ptm(20, 30);
PointToVoidMethof fsq = frst.FindSquareOfNumber;
fsq(2, 5);
ReadKey();
return 0;
}
I created a new instance of the class with object name frst and a new instance of the delegate.
Now i have referenced both methods with the delegates with the PointToMethod delegate. As you can see, I initialized both methods differently which is okay. But, it is advisable to initialize the method using the second technique, because the first technique is outdated.
The Image above shows the result of the code
Posted on Utopian.io - Rewarding Open Source Contributors
Your contribution cannot be approved because it is not as informative as other contributions. See the Utopian Rules. Contributions need to be informative and descriptive in order to help readers and developers understand them.
Hi, these are the reasons your contribution was rejected
I recommend you read the rules before contributing again in the future - make sure your future tutorials are more informative and professional.
You can contact us on Discord.
[utopian-moderator]