4 Replies - 695 Views - Last Post: 26 April 2017 - 05:18 PM

#1 Dialupp  Icon User is offline

  • D.I.C Head

Reputation: -2
  • View blog
  • Posts: 210
  • Joined: 31-October 16

Understanding delegates

Posted 26 April 2017 - 02:29 AM

Hey guys so I am having troubles to understand this code:

button.Click += delegate {
button.Text = string.Format ("{0} clicks!", count++);
};

so I did some research and the delegate has something to do with the event handler.

From code I can see we are adding button.Click's value to "button.Text = string.Format ("{0} clicks!", count++);" ? what does the delegate do here?

Is This A Good Question/Topic? 0
  • +

Replies To: Understanding delegates

#2 modi123_1  Icon User is offline

  • Suitor #2
  • member icon



Reputation: 13567
  • View blog
  • Posts: 54,133
  • Joined: 12-June 08

Re: Understanding delegates

Posted 26 April 2017 - 06:37 AM

Sort of. Delegates are encapsulated references to a method inside a delegate object. For all intent and purpose in this example it allows you to tell an event (button's click) to look at that delegate method when the event click is fired.

https://msdn.microso...9(v=vs.71).aspx
Was This Post Helpful? 0
  • +
  • -

#3 Dialupp  Icon User is offline

  • D.I.C Head

Reputation: -2
  • View blog
  • Posts: 210
  • Joined: 31-October 16

Re: Understanding delegates

Posted 26 April 2017 - 03:41 PM

Ok 1 more question why must we use the += operator or -= why can't we use just = ? with the = arent we saying the onclick is equal to the delegate method being called? Or is problem point of delegate methods is to call multiple methods if user wants? This syntax is very strange there isn't even a method name.
Was This Post Helpful? 0
  • +
  • -

#4 modi123_1  Icon User is offline

  • Suitor #2
  • member icon



Reputation: 13567
  • View blog
  • Posts: 54,133
  • Joined: 12-June 08

Re: Understanding delegates

Posted 26 April 2017 - 04:59 PM

It's not about assigning. In the background the delegate is added to a list of event delegates. Then again they could have used anything, but logically it makes sense to use the +=.

There's no method name, but there is the delegate object. Again.. handled behind the scenes.

You certainly could use a method as long as the signature was matching.
Was This Post Helpful? 0
  • +
  • -

#5 Dialupp  Icon User is offline

  • D.I.C Head

Reputation: -2
  • View blog
  • Posts: 210
  • Joined: 31-October 16

Re: Understanding delegates

Posted 26 April 2017 - 05:18 PM

Ah ok thanks.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1