Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delegates, Why? [duplicate]

Tags:

c#

delegates

Possible Duplicates:
When would you use delegates in C#?
The purpose of delegates

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.

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."

I don't understand how that statement is correct.

I've written the following examples. Let's say you have 3 methods with same parameters:

   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;     } 

Now I declare a delegate:

public delegate int Operations(int x, int y); 

Now I can take it a step further a declare a handler to use this delegate (or your delegate directly)

Call delegate:

MyClass f = new MyClass();  Operations p = new Operations(f.multiply); p.Invoke(5, 5); 

or call with handler

f.OperationsHandler = f.multiply; //just displaying result to text as an example textBoxDelegate.Text = f.OperationsHandler.Invoke(5, 5).ToString(); 

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?

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.

Can someone please give me a real world situation? I am totally confused.

like image 972
Mage Avatar asked Aug 25 '10 15:08

Mage


People also ask

Why is my Outlook calendar duplicating appointments?

Duplicate entries in Outlook Calendar can occur due to inconsistencies when importing, exporting or syncing your calendar data across multiple devices. You can prevent duplicates from appearing in your calendar by having the proper settings in place when using the application's Import/Export Wizard.

How do I copy a meeting invite in Outlook?

Copy or Duplicate Outlook meeting invites You can easily duplicate meeting entries in your Outlook calendar by highlighting the meeting in your Outlook Calendar view and simply copying it by hitting Ctrl+C , and then paste it to your preferred time by hitting Ctrl+V .

How do I copy a meeting in Outlook for Mac?

When you've logged in, right click the event you want to duplicate, and you should be able to click on the option to duplicate it.


2 Answers

Changing functionality at runtime is not what delegates accomplish.

Basically, delegates save you a crapload of typing.

For instance:

class Person {     public string Name { get; }     public int Age { get; }     public double Height { get; }     public double Weight { get; } }  IEnumerable<Person> people = GetPeople();  var orderedByName = people.OrderBy(p => p.Name); var orderedByAge = people.OrderBy(p => p.Age); var orderedByHeight = people.OrderBy(p => p.Height); var orderedByWeight = people.OrderBy(p => p.Weight); 

In the above code, the p => p.Name, p => p.Age, etc. are all lambda expressions that evaluate to Func<Person, T> delegates (where T is string, int, double, and double, respectively).

Now let's consider how we could've achieved the above without delegates. Instead of having the OrderBy method take a delegate parameter, we would have to forsake genericity and define these methods:

public static IEnumerable<Person> OrderByName(this IEnumerable<Person> people); public static IEnumerable<Person> OrderByAge(this IEnumerable<Person> people); public static IEnumerable<Person> OrderByHeight(this IEnumerable<Person> people); public static IEnumerable<Person> OrderByWeight(this IEnumerable<Person> people); 

This would totally suck. I mean, firstly, the code has become infinitely less reusable as it only applies to collections of the Person type. Additionally, we need to copy and paste the very same code four times, changing only 1 or 2 lines in each copy (where the relevant property of Person is referenced -- otherwise it would all look the same)! This would quickly become an unmaintainable mess.

So delegates allow you to make your code more reusable and more maintainable by abstracting away certain behaviors within code that can be switched in and out.

like image 119
Dan Tao Avatar answered Oct 14 '22 01:10

Dan Tao


.NET Delegates: A C# Bedtime Story

like image 27
PatrickSteele Avatar answered Oct 13 '22 23:10

PatrickSteele