0

I am trying to learn delegates in C# from this article http://msdn.microsoft.com/en-us/library/aa288459(v=vs.71).aspx

I am able to understand the code a bit but i am not able to understand where and why would a developer want to use delegates. Can somebody give an easy scenario which can help me start with delegates?

Update I read this statement everywhere, "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."

But why would i want compiler shouldn't know about function i pass? I can smell abstraction here but what's the use? Any real time scenario is required.

Charu
  • 2,679
  • 6
  • 35
  • 52
  • possible duplicate of [When would you use delegates in C#?](http://stackoverflow.com/questions/191153/when-would-you-use-delegates-in-c) – Magnus Johansson May 31 '12 at 09:59
  • @MagnusJohansson I have read this thread, and i dont get much out of it. I need a more basic example. I am not using lambda expressions nor anonymous functions. – Charu May 31 '12 at 10:01

4 Answers4

1

Look, in windows forms there are classes like button, image, textbox etc... All of them have event handlers like button.click, textbox.texchange, ... which are delegates themselves. and when you want to do something on button click you write function which is void and has two aguments: of object type and EventArgs. The one who wrote that button class didnot know what to do on button click but gave you delegate:

public delegate EventHandler Click;

where will be your defined methods like:

public void mymethod(object s, EventArgs e)

or every method tha is void and has that parameters

levi
  • 3,451
  • 6
  • 50
  • 86
1

A good example of using delegates would be callbacks. Imagine you have a class DbSearcher. That class has the method Search(string q) and when you call this method it takes it 1 minute to return. You want to eventually display results of the search but you don't want to keep the user waiting for them to appear while being unable to do anything more. What you do is you change your method to, for example, Search(string q, Action displayResults) and fire it in a separate thread. displayResults here is a delegate which you will call inside the Search method once the search results are retrieved from the db.

m1kael
  • 2,801
  • 1
  • 15
  • 14
  • but why do i have to pass in a delegate here? Can't i just pass the function name instead! This is where i am confused. I know what you are talking about is asynchronous programming and have used it as well, but why we are passing delegate here instead of just the function name is what i am confused with. – Charu May 31 '12 at 10:20
  • In either cases, you DO pass a delegate -- either inline or as a method's name. If you look at this from the other end (the end of the receiving side) you will see that the displayResults parameter of type Action (which is a delegate type) from the example above is what makes it possible for you to pass-in your method's name or inline delegate. A delegate is a variable whose value is a function. – m1kael May 31 '12 at 21:28
0

You can find so many example and code snippets over the web . Here is my example, think that your user is going to decide which operation he/she is going to do in the following,

  1. Add two numbers
  2. Subtract two numbers
  3. Multiple two numbers
  4. Divide two numbers.

But you have one common method to perform all this

Operation(some delgate method)
{
   // do some operation
}

u you can pass the delegate at run time based on user selection.

This is just an example.

Rajesh Subramanian
  • 6,400
  • 5
  • 29
  • 42
  • Why can't i just call the actual functions after getting user selection here. Just a thought, its perplexing! – Charu May 31 '12 at 10:15
0

A delegate is basically a reference to a method.

You can for example have to different methods for changing a string:

public static string ChangeOne(string s) {
  return s.TrimStart();
}

public static string ChangeTwo(string s) {
  return s.TrimEnd();
}

Depending on some criteria, you can choose between them, and put the choice in a delegate:

Func<string, string> change;
if (DateTime.Today.DayOfWeek == DayOfWeek.Sunday) {
  change = ChangeOne;
} else {
  change = ChangeTwo;
}

Then you can use the delegate just a regular method. The code that uses it doesn't have to know what the method does, or why:

string x = "  asdf  ";
x = change(x);

Delegates are for example widely used for generic collections, where the library methods doesn't have to know anything about the objects in the collection. You just provide it with a delegate to a method that picks out the relevant information.

Here the Where method doesn't know anything about the objects in the list, it only gets a delegate to a method that determines if an object should be included in the result or not:

IEnumerable<obj> older = listOfObj.Where(o => o.Age >= 18);
Guffa
  • 687,336
  • 108
  • 737
  • 1,005