Reputation: 313
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
Upvotes: 3
Views: 133
Reputation: 138137
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.
Upvotes: 5
Reputation: 8950
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.
Upvotes: 2