Click here to Skip to main content
15,900,725 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
While sufing on internet I found below code of delegates-----------

C#
public delegate int Calculate (int value1, int value2);

class MyClass
{
  public int add(int value1, int value2)
  {    
    return value1 + value2;            
  }

  public int sub( int value1, int value2)
  {    
    return value1 - value2;            
  }
}

MyClass mc = new MyClass();
Calculate add = new Calculate(mc.add);
Calculate sub = new Calculate(mc.sub);

Console.WriteLine("Adding two values: " + add(10, 6));
Console.WriteLine("Subtracting two values: " + sub(10,4));

-------But this can be done directly by calling class object also. So why we use delegates. Is it helpful to use it. Is it increase the performance of software.
Posted
Updated 4-Jul-12 17:17pm
v2

Of course people can live without delegates. Without OOP. Without electricity…

Bringing a pointless code sample found "on Internet" does not prove anything. Maybe, it's not so pointless, just the point could be different: to explain the syntax, basic usage, how things work in principle. Don't thing everyone needs to prove to you the usefulness of some activity. You just need to use some fantasy, first learn how things work and then decide how it can be used; this is much more productive.

The programming is all about abstractions. When one method calls another method, it uses the fact that the method is abstracted from the particular values of its parameters: the parameters are formal, and different actual parameters can be substituted, which provides some level of code reuse. Can the calling method be abstracted from the method it calls? Yes, it can, but then the methods should be able to be presented as parameters. To do this, we need to have some language construct and the concept that represents something which can be called as methods, but is a first-class citizen. That brings us to the idea of delegates. Fur further detail, read this:

http://en.wikipedia.org/wiki/Abstraction_%28computer_science%29[^],
http://en.wikipedia.org/wiki/First-class_function[^]
http://en.wikipedia.org/wiki/Delegation_%28programming%29[^].

There are situations where delegates provide dramatic improvement in performance, but such cases are very advanced and hard to explain. One of them is using such thing as System.Reflection.Emit.DynamicMethod:
http://msdn.microsoft.com/en-us/library/system.reflection.emit.dynamicmethod.aspx[^].

Explanation of the scenarios goes far beyond the topic of this question; and you are certainly not yet ready to understand such thing. Main focus of delegates is expressive capabilities, abstraction and code reuse, not performance. I notices that the thinking of the beginners often tries to reduce many non-trivial aspects of programming to performance. With some experience, this problem should go.

—SA
 
Share this answer
 
Comments
AmitGajjar 5-Jul-12 0:51am    
woow... what an explanation... 5+
Sergey Alexandrovich Kryukov 5-Jul-12 1:13am    
Thank you, Amit.
--SA
In this case, you very well knew which method to call right?
Now consider a scenario when you don't know the method you need to call.
The method will not be decided at compile-time but rather at runtime.

Delegates play a key role in Event handling.
Imagine a textbox that you place on the UI.
Now at runtime, when you press a key on the button, you have about 3-4 events that execute - KeyUp, KeyDown, GotFocus etc.
Attaching the right handlers would allow you to handle only those actions that are important to you.
 
Share this answer
 
What you have is a very basic example which is good for understanding how to implement delegates, but as with any basic example, it is contrived. This may be a better example: http://morkalork.com/mork/article/128/How_and_why_to_use_delegates_in_C[^]. This may not be of much help, you can look on the web for more examples that might be better for you.
 
Share this answer
 
Well for a simple example like this, effectively, one can call the function directly and it would be more efficient to do so (and also easier to understand).

Starting from your example, one could imagine a calculator. You can start with something like that:

C#
var dictionary = new Dictionary<string, Calculate>();
dictionary.Add("+", new Calculate(mc.add));
dictionary.Add("-", new Calculate(mc.sub));


Then you would have code that would parse user input. It would then be easy to execute the appropriate code depending on the operator and operands.

The main benefit is when you can reuse algorithms by calling a delegate. A good example is a comparison function that might be used in a search algorithm.
 
Share this answer
 
Comments
Sandeep Mewara 5-Jul-12 1:40am    
Countered 1 vote. Answer deserves more. Voted 5!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900