Note that there are some explanatory texts on larger screens.

plurals
  1. PODelegates, Why?
    text
    copied!<blockquote> <p><strong>Possible Duplicates:</strong><br> <a href="https://stackoverflow.com/questions/191153/when-would-you-use-delegates-in-c">When would you use delegates in C#?</a><br> <a href="https://stackoverflow.com/questions/687626/the-purpose-of-delegates">The purpose of delegates</a> </p> </blockquote> <p>I have seen many question regarding the use of delegates. I am still not clear where and WHY would you use delegates instead of calling the method directly.</p> <p>I have heard this phrase many times: "The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked."</p> <p>I don't understand how that statement is correct.</p> <p>I've written the following examples. Let's say you have 3 methods with same parameters:</p> <pre><code> public int add(int x, int y) { int total; return total = x + y; } public int multiply(int x, int y) { int total; return total = x * y; } public int subtract(int x, int y) { int total; return total = x - y; } </code></pre> <p>Now I declare a delegate:</p> <pre><code>public delegate int Operations(int x, int y); </code></pre> <p>Now I can take it a step further a declare a handler to use this delegate (or your delegate directly)</p> <p>Call delegate:</p> <pre><code>MyClass f = new MyClass(); Operations p = new Operations(f.multiply); p.Invoke(5, 5); </code></pre> <p>or call with handler</p> <pre><code>f.OperationsHandler = f.multiply; //just displaying result to text as an example textBoxDelegate.Text = f.OperationsHandler.Invoke(5, 5).ToString(); </code></pre> <p>In these both cases, I see my "multiply" method being specified. Why do people use the phrase "change functionality at runtime" or the one above?</p> <p>Why are delegates used if every time I declare a delegate, it needs a method to point to? and if it needs a method to point to, why not just call that method directly? It seems to me that I have to write more code to use delegates than just to use the functions directly.</p> <p>Can someone please give me a real world situation? I am totally confused.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload