?
Solved

Delegate in c#

Posted on 2011-04-21
8
Medium Priority
?
429 Views
Last Modified: 2012-05-11
I want to know when and why should i use delegate in my program in c#.
Is it only to encapsulates a reference to a method.
also what does it mean delegate( a= x+y ).
The url has been checked by me -
http://msdn.microsoft.com/en-us/library/ms173173(v=vs.80).aspx
but not clear
0
Comment
Question by:rnsr
  • 4
  • 4
8 Comments
 
LVL 10

Expert Comment

by:oxyoo
ID: 35440402
A delegate could be used when..

An eventing design pattern is used
It is desirable to encapsulate a static method
The caller has no need to access other properties, medhods, or interfaces on the object implementing the method
Easy composition is desired
A class may need more than one implementation of the method

Ref: http://msdn.microsoft.com/en-us/library/ms173173(v=vs.80).aspx
0
 
LVL 10

Accepted Solution

by:
oxyoo earned 1500 total points
ID: 35440442
The idea behind a delegate is that it allows you to specify what the function you want to call looks like without having to specify which function to call.

The benefit of this is that you do not need to know at compile time which method will be invoked.


Hope that helps.
0
 
LVL 10

Expert Comment

by:oxyoo
ID: 35440472
More examples of where you could use delegates is with Event handlers, Linq, and callbacks (async).
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:rnsr
ID: 35440609
Refer to it -
  MyDelegate del1 = new MyDelegate(MyClass.Add);
 int result = del1(5,5);

this example i had taken from web site.
here i am using function add which is the method of class MyClass.
I had specified the Method add .
so where am i hiding the function.

Plz help me to clear the concept.
0
 

Author Comment

by:rnsr
ID: 35451824
I need some clearification  about  with example in c# if possible --
-- The caller has no need to access other properties, medhods, or interfaces on    
    the object implementing the method
-- Easy composition is desired
--  A class may need more than one implementation of the method

Thanks
0
 
LVL 10

Expert Comment

by:oxyoo
ID: 35464707
Sorry for late response (easter weekend :o) )...
Here's is an attempt to see if I can clarify delegates a bit more...

I have created a Logger class, this class contains a delegate (LogHandler), it is the LogHandler's responsibility to log whatever the user wants. To make this more flexible (in the future, multiple different logger might be needed) the user must provide a log handler for us (sending it in via the constructor).

Then there are the two Implemented Logger classes (Console and FormattedConsole), which we will use to log the messages in a slightly different way.

We can now, easily, create loggers with different behavior without the need to change the Logger class. Just pass any of the loggers in as delegates into the constructor of the Logger.


Hope this helps!

using System;

public class Logger {
  public delegate void LogHandler(string message);

  private readonly LogHandler _logHandler;

  public Logger(LogHandler logHandler) {
    if(logHandler == null ) throw new ArgumentException("logHandler not correctly initialized.");
    _logHandler = logHandler;
  }

  public void Log(string message) {
    _logHandler(message);
  }
}


public class ConsoleLogger {
  public static void Logger(string message) {
    Console.WriteLine(message);
  }
}

public class FormattedConsoleLogger {
  public static void Logger(string message) {
    Console.WriteLine(string.Format("Someone logged: {0}", message));
  }
}


public class Delegate {
  public void Execute() {
    var logger = new Logger(ConsoleLogger.Logger);
    var formattedLogger = new Logger(FormattedConsoleLogger.Logger);


    logger.Log("Hello, World!");
    formattedLogger.Log("Hello, World!");
  }
}

Open in new window

0
 

Author Comment

by:rnsr
ID: 35506971
I am busy and will write comment soon.
Thanks
0
 

Author Closing Comment

by:rnsr
ID: 35921062
nice to learn
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

After several hours of googling I could not gather any information on this topic. There are several ways of controlling the USB port connected to any storage device. The best example of that is by changing the registry value of "HKEY_LOCAL_MACHINE\S…
For a while now I'v been searching for a circular progress control, much like the one you get when first starting your Silverlight application. I found a couple that were written in WPF and there were a few written in Silverlight, but all appeared o…
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
Are you ready to place your question in front of subject-matter experts for more timely responses? With the release of Priority Question, Premium Members, Team Accounts and Qualified Experts can now identify the emergent level of their issue, signal…

840 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question