Why is trying to understand what delegates feel they are trying to understand the nature of the universe?

I read two books, many examples. They still don't make any sense to me. Perhaps I could write code that uses delegates, but I have no idea why. Am I alone with this problem, or am I just an idiot? If someone can explain to me when, where and why I really use a delegate, I will love you forever.

+47
c # delegates
Apr 20 '10 at 21:07
source share
8 answers

Delegates are just a way to pass a function into a variable.

You pass a delegated function to perform a callback. For example, when performing asynchronous I / O, you pass a delegated function (a function that you wrote with the delegation parameter) that will be called when the data has been read from disk.

+18
Apr 20 '10 at 21:12
source share

As other people have said, delegates are convenient for callbacks. They are useful for the whole load of other things. For example, in a game in which I worked on recent bullets, different things are done when they fall (some cause damage, some actually increase the health of the person they hit, some do no damage, but poison the target, etc.) . The classic OOP way for this would be a bullet base class and loading subclasses

Bullet DamageBullet HealBullet PoisonBullet DoSomethingElseBullet PoisonAndThenHealBullet FooAndBarBullet .... 

With this pattern, I have to define a new subclass every time I need some new behavior in the pool, which is a mess and leads to a lot of duplicate code. Instead, I solved it with delegates. The bullet has an OnHit delegate that gets called when the bullet hits the object, and of course I can make this delegate anything. So now I can create such bullets

 new Bullet(DamageDelegate) 

This is obviously a much better way to do something.

In functional languages, you tend to see much more of this kind of thing.

+4
Apr 20 '10 at 21:28
source share

A delegate is a simple container that knows where a particular method resides in the computerโ€™s memory.

All delegates have an Invoke(...) method, so when someone has a delegate, they can actually execute it without having to know or worry about what this method actually does.

This is especially useful for decoupling. Graphical GUIs would not have been possible without this concept, because Button simply does not know anything about your program that you intend to use it in, so it cannot call your methods by itself whenever it is clicked. Instead, you should specify which methods it should call when clicked.

I think you are familiar with the events, and you regularly use them. The event field is actually a list of such delegates (also called a multi-sheet delegate). Maybe things will become clearer when we look at how we could "simulate" events in C # if it did not have the keyword event , but only (not multicast) delegates:

 public class Button : Rectangle { private List<Delegate> _delegatesToNotifyForClick = new List<Delegate>(); public void PleaseNotifyMeWhenClicked(Delegate d) { this._delegatesToNotifyForClick.Add(d); } // ... protected void GuiEngineToldMeSomeoneClickedMouseButtonInsideOfMyRectangle() { foreach (Delegate d in this._delegatesToNotifyForClick) { d.Invoke(this, this._someArgument); } } } // Then use that button in your form public class MyForm : Form { public MyForm() { Button myButton = new Button(); myButton.PleaseNotifyMeWhenClicked(new Delegate(this.ShowMessage)); } private void ShowMessage() { MessageBox.Show("I know that the button was clicked! :))))"); } } 

Hope I can help a bit .; -)

+4
Apr 20 '10 at 21:40
source share

This article from Chris Sells can help:

. NET delegates: C # Bedtime Story

+4
Apr 20 '10 at 21:45
source share

Perhaps this helps:

  • A delegate is a type (defining a method signature)
  • A delegate instance is a method reference (AKA function pointer)
  • Callback is a delegate type parameter
  • An event is a (kind of) delegate type property

The goal of delegates is that you can have variables / fields / parameters / properties (events) that "hold" the function. This allows you to store / transfer a specific function selected at runtime. Without it, every function call must be fixed at compile time.

The syntax involving delegates (or events) can be a bit complicated at first, for two reasons:

  • simple pointers to functions like in C / C ++ would not be type safe, in .NET the compiler does generate a class around it and then tries to hide it as much as possible.

  • delegates are the cornerstone of LINQ, and there is a steep evolution from describing everything in C # 1 using anonymous methods (C # 2) to lambdas (C # 3).

Just check out 1 or 2 standard templates.

+2
Apr 20 '10 at 21:11
source share

Come on guys! All of you have successfully complicated DELEGATES :)!

I will try to leave a hint here: I understood delegates as soon as I realized what jquery ajax calls in Javascript. for ex: ajax.send (url, data, successcallback, failcallback) is the signature of the function. as you know, it sends data to the server url, as the answer, maybe 200OK or some other error. In the event of any such event (success / failure), you want to execute the function. Thus, it acts as a placeholder for the function to be able to mention either success or failure. This placeholder may not be very general - it may take a set of parameters and may / may not return a value. This is a declaration of such a Placeholder, if made in C # IS CALLED DELEGATE! Since javascript functions are not strict with the number of arguments, you just see them as GENERIC placeholders ... but C # has some STRICT declarations ... it comes down to DELEGATE declarations !!

Hope this helps!

+1
Apr 27 '15 at 9:10
source share

A delegate is a pointer to a safe function of a type , that is, a delegate points to a function , when a delegate function is called, the actual function will be called . It is mainly used in developing core applications. When we want to separate logic, we can use a delegate. Those. instead of manually encoding in a specific method, we can pass the delegate to the function and set another functional logic inside the delegate function . Delegates add flexibility to your infrastructure.

Example: how to use it

 class program { public static void Main) { List<Employee> empList = new List<Employee> () { new Employee () {Name = "Test1", Experience = 6 }, new Employee () {Name = "Test2", Experience = 2 }, } // delegate point to the actual function IsPromotable isEligibleToPromote = new IsPromotable(IsEligibleToPromoteEmployee) Employee emp = new Employee(); // pass the delegate to a method where the delegate will be invoked. emp.PromoteEmployee(empList, isEligibleToPromote); // same can be achieved using lambda empression no need to declare delegate emp.PromoteEmployee (empList, emply =>emply.Experience > 2); // this condition can change at calling end public static bool IsEligibleToPromoteEmployee (emp){ if (emp.Experience > 5) return true; else return false; } } } public delegate bool IsPromotable(Employee emp); public class Employee { public string Name {get; set;} public int Experience {get; set;} // conditions changes it can 5, 6 years to promote public void PromoteEmployee (List<Employee> employees, IsPromotable isEligibleToPromote) { foreach (var employee in employees) { // invoke actual function if (isEligibleToPromote(employee)){ Console.WriteLine("Promoted"); } } } 
0
Nov 19 '17 at 6:00
source share

I don't think anyone mentioned this, but the section on John Skeet's delegates in his book โ€œ C # in depth โ€ is probably the best I've ever met. Just like the OP, I fought with the delegates. I had a problem setting delegates.

The book "John Skeet" is great for explaining delegates, because it breaks the delegate up "tuned", gives explanations between the type of delegation and the instance of delegation (you will need to understand that the book in order to understand this, otherwise I may open myself up for copyright infringement right, because I could not explain it better than John). Best of all, he gives a small but clear example.

I am in no way affiliated with John Skeet or Manning, but it is worth reading, and not just for the delegates section.

-one
Oct 24 '11 at 20:28
source share



All Articles