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.
I like it when individuals get together and share opinions.
Great blog, keep it up!
@Zsolt
cooperate link/DHs
leave a reply
Duh, I just saw the original post which _is_ focused on this! Silly me! Next time I’ll read more thoroughly!
Because the post title read “under the hood” I was expecting more in-detail description on what events and delegates are than “try it out and you’ll get a compile error if you don’t type it like this”.
Looking forward for a real under the hood post on what events and delegates are and what the difference between them is!