static void Main(string[] args) { var classWithMethodsMatchingEventTypes = new ClassWithMethodsMatchingEventTypes(); // 1. Demonstrate how do "add" and "remove" accessors of event property work. var p = new Program(); p.MyEvent += new EventHandler(classWithMethodsMatchingEventTypes.DoNothing); p.MyEvent -= null; // It does not matter that we are passing null, "remove" accessor code is executed. // 2. Attach the handler to an event declared using "shorthand" notation. var classWithTheShorthandEventProp = new ShorthandEventAndBackingDelegateDeclaration(); classWithTheShorthandEventProp.NewMessage += new EventHandler <NewMessageEventArgs> (classWithMethodsMatchingEventTypes.LogEventToConsole); NewMessageEventArgs eventArgs = new NewMessageEventArgs { Message = "Hello! It's a brand new message" }; // Raise the event. classWithTheShorthandEventProp.OnNewMessage(eventArgs); }
// The above is translated to the following in C# 1.1: // private EventHandler<NewMessageEventArgs> _newMessage; // // public event EventHandler<NewMessageEventArgs> NewMessage // { // add // { // lock (this) // { // _newMessage += value; // } // } // remove // { // lock (this) // { // _newMessage -= value; // } // } // } /// <summary> /// Raises the NewMessage event. /// </summary> public virtual void OnNewMessage(NewMessageEventArgs e) { NewMessage?.Invoke(this, e); }
public void LogEventToConsole(object sender, NewMessageEventArgs e) { Console.WriteLine(e.Message); }