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”);
- }
- }
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++)
- {
- // does something
- obj(i);
- }
- }
- }
- }
- }
Summary
In this blog, we have discussed the real use of delegate in C# with a simple program.

ramlalPosted Jul 19, 2020, 3:34 AM
Good and simple example. kindly keep it up.