Stuck trying to figure out delegates

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

With this code:

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

      

Two copies are printed on the screen.

However with this code:

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

      

Only one instance is displayed on the screen. Behavior like this code:

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

      

Someone please enlighten me on the basics of delegates in C #. I am still a newbie and get lost when I try to break down and go into the code itself. My weak attempt at explaining the behavior for myself is that if you run a delegate with multiple sheets, the use cases must be multi-sheet as well.

Any result that helps me understand the concept is greatly appreciated: D

+3


source to share


2 answers


Suppose you have

const int oneBook = 1;
int bookCounter = 0;

      

Your first block of code is equivalent to:

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

      



The second code block is equivalent:

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

      

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

+5


source


Basically the + = syntax is allowed for this:

book.NameChanged = book.NameChanged + OnNameChange; 

      

And the delegate type overrides the + operator by creating a MulticastDelegate that binds method calls. Delegates support addition and subtraction as operations of adding / subtracting functions from the call list. (As mentioned in the comments, the + doesn't actually add the function to the invocation list, instead a new multicast delegate is created for the result).



If you want to suppress the = create statement, create an event.

public event EventHandler NameChanged;

      

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

+2


source







All Articles