Events and Delegates Under The Hood – Q&A


In the comments from this morning’s post, Andrew raised two questions important enough that I wanted to answer them in a post, rather than in comments….

[In the original version of the posting] you had some code showing that you could use “=” with delegates but that you’d get a compile time error with the event keyword.

Answer: The easiest way to see this is to try it.  Change the assignment of the event handler from += to = in MainPageLoaded()

void MainPageLoaded(object sender, RoutedEventArgs e)
    var t = new Timer();
    t.SecondChanged = UpdateDisplay;

You should get an error on compile much like this:

Error    1
The event 'Clock.Timer.SecondChanged' can only appear
on the left hand side of += or -= (except when used from
within the type 'Clock.Timer')
C:\Code\Clock\Clock\MainPage.xaml.cs    18    15    Clock

Now, remove the keyword event in the Clock.cs file (returning SecondChanged to being a delegate). Rebuild and the compile error is gone.  It was the event keyword that prevented you from using the assignment operator

[Can you provide an example of] what you mean by  “Can only be called by methods of the class that defines the event”.

Answer: You can see this at work by returning to MainPageLoaded and typing a t followed by a dot after the two lines that are already there. With the keyword Event, you are offered access to the event which you can register with, but not invoke (first image below).  If, as in the previous answer, you remove the keyword event in Timer, when you enter t. in MainPageLoaded you are offered the delegate (second image below), which you can use to call the handler directly from outside the Timer class.


About Jesse Liberty

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen Pluralsight & LinkedIn Learning courses. He was a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Xamarin Certified Mobile Developer and a Xamarin MVP and a Microsoft MVP.
This entry was posted in Languages, Mini-Tutorial, Tools and Utilities and tagged , . Bookmark the permalink.

7 Responses to Events and Delegates Under The Hood – Q&A

Comments are closed.