Introduction
In this post, we will talk about delegates and their real use. Usually, in an interview, people will say a delegate is nothing but a pointer to a function. When looking at this definition, it looks very stupid.
What is a delegate?
Let’s discuss it with a simple program when we say a delegate is a pointer to a function.
- class program {
- public delegate void somemethodptr()
- static void Main(string[] args) {
- somemethodptr obj = new somemethodptr(somemethod);
- obj.Invoke();
- }
- static void somemethod() {
- console.WriteLine(“Method called”);
- }
- }
In the above program, I am creating a delegate by creating an object pointing to a method. if I run the above program it will work without any issues, but does it make sense? So now the question is a method can call directly what is the use of calling indirectly? so in order to understand delegate really check in the dictionary what the meaning of delegate word is delegate is kind of representation. The main goal of the representator is to communicate between two parties.
The actual definition in C# delegate is meant to do communication between two things. Let me explain what it is a delegate.
Now assume for example you have class myclass this class having long-running method. I am calling myclass in the main method. Now we have two parties one party is the main program another one myclass.
Let us say first-party wants to get information on which number is running for a loop. It means the first party wants to get live updates.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
-
- namespace Delegateexample
- {
- class Program
- {
- static void Main(string[] args)
- {
- myclass obj = new myclass();
- obj.longrunningmethod(callback);
-
- }
-
- static void callback(int i)
- {
- Console.WriteLine(i);
- }
- public class myclass
- {
- public delegate void callback(int i);
- public void longrunningmethod( callback obj)
- {
- for (int i = 0; i <= 100; i++)
- {
-
- obj(i);
- }
-
- }
-
-
- }
- }
- }
In the below program, what we are done is myclass is saying send me to delegate via call back method and it ensues I will make a callback method with the current number. In other words, myclass is communicating via delegate, In other words, the use of delegates is callbacks.
Summary
In this blog, we have discussed the real use of delegate in C# with a simple program.