Hi, I'm a naive to C#, trying to understand Delegate. I have read few articles describing delegate as
- - Type-safe function pointer
- - Used to define callback functions (methods that have something to-return)
- - Call multiple methods on single event
As C# is Object-Oriented & every object can be related to a real world entity, i believe delegates in real-world are 'people from one country/ team/ organization'
> Trump says North Korea **delegates** will deliver letter from Kim Jong Un about summit.
> Delegates from Microsoft talk about Github acquisition.
So delegate will have same parameters and return type as of underlying method the delegate refers to. As per https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/delegates/#delegates-overview
1. Delegates allow methods to be passed as parameters. - We can also pass methods as parameters to other methods. Console.WriteLine(foo.ToString());
2. Delegates can be used to define callback methods. - Methods with return keyword perform as delegates, because delegate is just a bridge between callee and caller methods.
3. Delegates can be chained together; for example, multiple methods can
be called on a single event. - As methods can also be chained.
- Caller method()
- {
- // Callee method1();
- Callee method2();
- // Callee method3();
- }
which could also be invkoed from single event
I assume, we see delegates working in background when we copy/cut & paste files/folders from Source to Destination. Because files are moved from source to Destination but how does progress-bar window know about current fileName & amount of progress to be filled in progress-bar.?
So, Why & When to use delegate? (As delegate points to a function which has required functionality to execute, why can't i call a function directly instead calling delegate?)
P.S @all C# corner members/ users - Please help me to understand delegate in & out.
Thanks in advance.
James AxsomPosted Jun 25, 2018, 10:04 AM
Sahil SharmaPosted Jun 25, 2018, 8:02 AM
One simple example about delegate usage is Publisher-Subscriber pattern. Let's say I ask to write a program to execute ten different functions (same structure) on a single button click. How will you do that?
Either yopu can call ten functions individualy or attach them to a delegate and simply invoke the delegate. This is why and where we use delegates. Cheers!