Events and Delegates Under The Hood – Q&A

MiniTutorial

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.

EventBlocksInvocationDelegateAlllowsInvocation

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 online courses. His latest book, Building APIs with .NET will be released early in 2025. Liberty is a Senior SW Engineer for CNH and 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 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.