C # Delegates Real world use

Earlier I asked a question that delegates have someone who has a scenario where I have to use a delegate? How will this improve my C # code?

Just like many scripts that I use in it, it always seems to me that you can program around it.

+6
source share
11 answers

Assuming you are not talking about events - of course, you can program around it. The point is to make it more enjoyable and clean .

protected void Sort() { foreach (string key in _dBase.Keys) { Array.Sort<Pair<string, Dictionary<string, T>>>(_dBase[key], new Comparison<Pair<string, Dictionary<string, T>>>( delegate(Pair<string, Dictionary<string, T>> a, Pair<string, Dictionary<string, T>> b) { if (a == null && b != null) return 1; else if (a != null && b == null) return -1; else if (a == null && b == null) return 0; else return a.First.CompareTo(b.First); })); } } 

Can I do this without a built in delegate? Of course. Will I have a flexible private method in my class that will only be used for this single instance? Yes.

Edit: As mentioned in the comments, you can simplify:

 Array.Sort<Pair<string, Dictionary<string, T>>>(_dBase[key], new Comparison<Pair<string, Dictionary<string, T>>>( delegate(Pair<string, Dictionary<string, T>> a, Pair<string, Dictionary<string, T>> b) { 

to

 Array.Sort<Pair<string, Dictionary<string, T>>>(_dBase[key], (a,b) => { 
+3
source share

Whenever you use a strategy template or an observer template, delegates make your work a lot easier than using interfaces.

+4
source share

If you represent C # without delegates, you usually come across situations where you have classes or interfaces with one method. The name of this method is redundant. eg.

 public interface IGetMail { Mail JustGetTheMail(); } 

This interface uses one method. A reference to an object of this type is really nothing more than a reference to a single method being called. Caller Code:

 Mail m = getMail.JustGetTheMail(); 

can be reduced to:

 Mail m = getMail(); 

The compiler can do this as โ€œsyntactic sugarโ€ without any ambiguity, because there is only one method that you could call in this getMail link.

So add this function to our C # compiler. Now, when we declare these types, we could do it a little more accurately. We do not need to specify the name of the method when calling, so why should we first specify the name method?

Choose the name of the standard method, Invoke , i.e.

 public interface IGetMail { Mail Invoke(); } 

We will add some more syntactic sugar so that we can write this as:

 public delegate Mail GetMail(); 

Hey presto. We have added delegates to our C # compiler.

(Technically, the CLR also knows about delegates, and instead of generating an interface, the C # compiler generates a special type of "delegate" that supports asynchronous invocation and manipulates an immutable list of delegates and treats them as a single reference, but this could be done in basic form with interfaces. There is a suggestion to do this for Java).

Then we can go further and add anonymous delegates - make them compressed for implementation so that the interfaces are not.

So, to answer your question - at any time when your interface has one method, it can be a delegate, and you can seriously reduce the amount of unnecessary code that you have to write.

+3
source share

No one mentioned this, but if you use LINQ with Lambda, you use anonymous methods all the time. Which are technically still delegates .

Let's say you have a class called Person

 class Person { public string FirstName { get; set; } public string LastName { get; set; } } 

And you wanted to implement a find method in which you find a person based on your FirstName

 public Person Where(List<Person> list, string firstName) { //find the string foreach(Person item in list) if(item.FirstName.Equals(firstName)) return item; } 

This is a very specific search, not a very dynamic one, that is, if you want to search by LastName, you will have to change this method or write a new one.

Fortunately, LINQ provides an extension method for Where to delegate to. which you can create on the fly using anonymous methods.

eg

 string searchString = "Stan"; list.Where( person => person.FirstName.Equals(searchString)); 

but if you want to go to search on LastName, you just do it

 string searchString = "R"; list.Where( person => person.LastName.Equals(searchString)); 

This example may not be what you were looking for, but I just wanted to show that sometimes we use delegates all the time, without thinking about it or not understanding it.

+3
source share

Use of the real world:

  • Suppose you have a simple Checker user control - which consists of only two flags - chkA and chkB.
  • Inside the user control, you can control the check / uncheck events by implementing the corresponding events for chkA and ChkB

3. Now, in the new Win form, when dragging Checker ... and your goal is to make sure that when you click chkA you need to change the background color of the label ... lblColorPicker.

Remember that lblColorPicker is a control that exists on the form and is not directly related to Checker .

How do you achieve this?

Answer:

  • First you need to create a new event for your custom Checker control.
  • To create this new event, the first thing would be to create a delegate in the user control, and then use that delegate as the defining type for the new event that you are writing.
  • And then this event should be mapped to chkA ... an event in your user control.

This way you can control chkA ... through a new event from any new form, referencing the event ... through the delegate that you just wrote.

So much to use in the real world!

This goal CANNOT be achieved without writing a delegate.

Let me know if you think otherwise ... or if you need more details.

+3
source share

Anonymous delegates make the code more readable in some cases (you do not need to switch to another method to see the code that belongs to your method:

Winforms example

 class MyForm:Form{ //... protected override void OnLoad(EventArg e){ this.Cursor=Cursors.Wait(); this.Enabled=false; // do a long running DB operation without blocking the UI Thread ThreadPool.QueueUserWorkItem(state=>{ DoLongDBOperation(); // re enable the form BeginInvoke(new Action(()=>{ this.Cursor=Cursors.Default;this.Enabled=true;})); }); } 
+2
source share

Delegates are absolutely necessary if you add events to your class or do something asynchronous (there are several other good reasons for delegates). The benefits are that it is a very flexible approach.

+1
source share

I think you mean the definition of custom delegates?

EventHandler minimized the requirement for custom delegate definitions, but they are still useful if you want to add additional parameters to the method signature.

+1
source share

Whenever you need to change or change any properties of a winForms control, you need to use a delegate to pass control back to the stream created by the control ... to name just one of many examples.

+1
source share

One example would be the pub / sub message manager. You will need to register events with the dispatcher, and then call them accordingly. This allows you to easily connect disparate pieces of code. I can't think of a way to do this without using delegates

+1
source share

Let's say you have a console application that responds to various keystrokes:

  Action a = () => {/* Do Stuff*/}; Action b = () => {/* Do Stuff*/}; Action c = () => {/* Do Stuff*/}; Action d = () => {/* Do Stuff*/}; Action e = () => {/* Do Stuff*/}; Action f = () => {/* Do Stuff*/}; Action g = () => {/* Do Stuff*/}; Action h = () => {/* Do Stuff*/}; Action i = () => {/* Do Stuff*/}; Action j = () => {/* Do Stuff*/}; List<Action> actions = new List<Action>() {a,b,c,d,e,f,g,h,i,j}; string line; while((line = Console.ReadKey().KeyChar) != 'q') { if(line.isBetween_0_and_9()) { actions[line.ParseInt()](); } } 

Maybe you are just using a bunch of Ifs, but it is not only simpler, but also almost certainly more understandable / readable.

+1
source share

All Articles