L A

L A

  • NA
  • 170
  • 170.2k

Elucidate delegates C#

Jun 23 2018 3:43 PM
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.
  1. Caller method()  
  2. {  
  3.    // Callee method1();  
  4.       Callee method2();  
  5.    // Callee method3();  
  6. }  
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.
 

Answers (2)