Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stuck trying to understand delegates

Tags:

c#

book is an object, Namechanged is a field of type delegate, OnNameChange is a method the delegate can point to;OnNameChange simply writes to the console window

With this code:

        book.NameChanged = OnNameChange;
        book.NameChanged += OnNameChange;

Two instances print out to the screen.

However with this code:

        book.NameChanged += OnNameChange;
        book.NameChanged = OnNameChange;

Only one instance print out to the screen.Same behavior as this code:

        book.NameChanged = OnNameChange;
        book.NameChanged = OnNameChange;

Someone please enlighten me about the basics of delegates in C#. I'm still a beginner and gets lost when I try to break and step into the code itself. My weak attempt on explaining the behavior to myself is that if you start a multi-cast delegate, the succeding casts should also be multi-cast.

Any output to help me grasp the concept is much appreciated :D

like image 785
Practical Programmer Avatar asked Nov 21 '25 00:11

Practical Programmer


2 Answers

Suppose you have

const int oneBook = 1;
int bookCounter = 0;

Your first code block is equivalent to:

// bookCounter == 0
bookCounter = oneBook;
// bookCounter == 1
bookCounter += oneBook;
// bookCounter == 2

Your second code block is equivalent to:

// bookCounter == 0
bookCounter += oneBook;
// bookCounter == 1
bookCounter = oneBook;
// bookCounter == 1

Delegates behave very similarly, but with functions that execute code instead of a number being incremented.

like image 159
Kobi Avatar answered Nov 23 '25 14:11

Kobi


Basically the += syntax is resolved to this:

book.NameChanged = book.NameChanged + OnNameChange; 

And the delegate type overrides the + operator creating a MulticastDelegate chaining the method calls. Delegates do support add and subtract as operations to add/substract functions from a invocation list. (As mentioned in the comments the + does not really add a function to the invocation list, instead a new multicast delegate is created for the result).

If you want to suppress the = operator create a event.

public event EventHandler NameChanged;

Now the = operator is not valid outside the defining class.

like image 43
quadroid Avatar answered Nov 23 '25 13:11

quadroid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!