Click here to Skip to main content
15,911,896 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all,

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

This is a delegate declaration. We are calling class methods using delegate objects like this
Calculate add = new Calculate(mc.add);
Calculate sub = new Calculate(mc.sub);


we can call this methods through class objects. But why we use this delegates?
what are the advantages of delegates. Please explain with example.


Thanks in advance,
Rajkumar.C
Posted
Updated 2-Jun-12 1:32am
v2

They're a great way of encapsulating a piece of code. For instance, when you attach an event handler to the button, that handler is a delegate. The button doesn't need to know what it does, just how to call it at the right time.

Another example is LINQ - filtering, projecting etc all require the same kind of template code; all that changes is the logic to represent the filter, the projection etc. With lambda expressions in C# 3 (which are converted into delegates or expression trees) this makes it really simple:

C#
var namesOfAdults = people.Where(person => person.Age >= 18) 
                          .Select(person => person.Name); 


(That can also be represented as a query expression, but let's not stray too far from delegates.)

Another way of thinking of a delegate is as a single-method interface type. For example, the EventHandler delegate type is a bit like:
C#
public interface IEventHandler 
{ 
    void Invoke(object sender, EventArgs e) 
} 


But the delegate support in the framework allows delegates to be chained together, invoked asynchronously, used as event handlers etc.
 
Share this answer
 
Comments
VJ Reddy 2-Jun-12 11:58am    
Nice answer. 5!
Manas Bhardwaj 3-Jun-12 11:12am    
thanks!
Prasad_Kulkarni 3-Jun-12 1:36am    
My 5!
Manas Bhardwaj 3-Jun-12 11:12am    
thanks :)
 
Share this answer
 
v2
Comments
Prasad_Kulkarni 3-Jun-12 1:35am    
5'ed
Delegates are like providing reference to the function at run time.
Suppose we have various methods that follow a delegate and that we need to call those methods on some event or action ,in such scenario we need to use the delegate .Multicast delegates can be handy where we need to provide separate instance for each of the calling methods.


EXAMPLE ::->

C#
public delegate void MulticastDelegate(int num);// Declaring a delegate..

class Implement
{
   public int num1,num2;
   Implement()
   {
    num1=10;
    num2=5;
   }
    public static void add(int num1,int num2)
      {  
     //Apply some Logic 
      }
    public static void subtract(int num1,int num2)
     {
      //Apply some Logic
     }
   public static void Main()
   {
     MulticastDelegate addDelgate= new MulticastDelegate(add);//Declare an instance of the Delegate..
     addDelegate(Num1,Num2);//Calling the Delegate to perform the Function.
     MulticastDelegate subDelegate= new MulticastDelegate(subtract);//Declare an instance of the Delegate..
     subDelegate(Num1,Num2);//Calling the Delegate to perform the Function.
     Console.Read();
   }

}
 
Share this answer
 
v2
http://www.akadia.com/services/dotnet_delegates_and_events.html[^]

Read the Solution for better understanding..
 
Share this answer
 
First the example as you requested:
C#
void Verbose(string s) { Console.WriteLine(s); }
void Quiet(string s) {}
...
delegate void Print(string s);
...
void DoSomething(Print logger)
{
   logger("start...");
   ...
   logger("...done");
}

...
DoSomething(Verbose); // Note: don't call Verbose(), only refer to it
...
DoSomething(Quiet); // Note: don't call Quiet(), only refer to it
...


This is a possible usage.

If ever possible, use interfaces instead of delegates.

C#
public interface ILogging { void Print(string s); }
public class Verbose: ILogging
{
    public void Print(sting s) { Console.WriteLine(s); }
}
public class Quiet: ILogging
{
    public void Print(string s) {}
}
...
void DoSomething(ILogging logger)
{
   logger.Print("start...");
   ...
   logger.Print("...done");
}
...
DoSomething(new Verbose());
...
DoSomething(new Quiet());
...


It's more robust and more universally usable.

But C# interfaces have limits:
- no static methods possible in interfaces

E.g. I cannot tell something like (this does *not* compile):
C#
public interface ILogging { static void Print(string s); }
public class Verbose: ILogging
{
    public static void Print(sting s) { Console.WriteLine(s); }
}
public class Quiet: ILogging
{
    public static void Print(string s) {}
}
...
void DoSomething<T>() where T: ILogger
{
   T.Print("start...");
   ...
   T.Print("...done");
}
...
DoSomething<Verbose>();
...
DoSomething<Quiet>();
...


Here, you are bound to either having a "seed" object of a class that implements the interfaces (see 2nd example above) or to use delegates (see 1st example).

Cheers
Andi
 
Share this answer
 

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