// Chapter 8 Notes // Delegates and Events /* Delegate is going to allow us to pass methods as a parameters, return method send to variable Events notifications between objects */ // Program Code // Define a delegate for the event handler using System.Runtime.CompilerServices; public delegate void ContactAddedEventHandler(object sender, ContactEventArgs e); // param 2 args //public delegate void ContactDeletedEventHandler(object sender, ContactEventArgs e); // param 2 args // Custom events arguments // optionally > pass any data related to the event public class ContactEventArgs : EventArgs { // Args public string FirstName // "Philip" { get; } public string LastName // "Matusiak" { get; } public int Age // 21 { get; } // Constructor Statement ClassName() // local var getter = param definition public ContactEventArgs(string firstName, string lastName, int age) { // getter = param FirstName = firstName; LastName = lastName; Age = age; } // constructor } // ContactEventArgs // Contact Class // manage data model, contacts and trigger public class Contacts { // Event declaration // access objectType ClassType varName public event ContactAddedEventHandler ContactAdded; //public string contactAdded; // access type name // Method to add a new contact public void AddContact(string firstName, string lastName, int age) { // Add contact logic // 2 string types and the int type FAIL don't match Console.WriteLine("Do add logic here..."); Console.WriteLine(firstName); Console.WriteLine(lastName); Console.WriteLine(age); // Trigger the event // some type of onName function // protected method OnContactAdded(new ContactEventArgs(firstName, lastName, age)); } // AddContact // Method to raise the event onName protected virtual void OnContactAdded(ContactEventArgs e) { // kick off or Invoke or publish to Any subscribers listening to this event ContactAdded?.Invoke(this, e); // new Action(()=>ops) } // OnContactAdded } // Contacts // Program Class class Program { static void Main(string[] args) { // Welcome to my app Console.WriteLine("=== Welcome to my App"); // Create an Instance of the Contacts Class Contacts contacts = new Contacts(); // Tuple immutable, indexed, defined contacts.AddContact("Bob", "Smith", 21); // Subscriber > to a specific event contacts.ContactAdded += Contacts_ContactAdded; // optionally > unsubscribe contacts.ContactAdded -= Contacts_ContactAdded; // Footer Console.WriteLine("=== Footer ==="); } // Main // // Event Handler Method for the Program /* * private static void Contacts_ContactAdded(object sender, ContactEventArgs e) */ // Anonymous Object private static void Contacts_ContactAdded(object sender, object e) // replacing ClassType with refType { // Anonymous Type var addedContact = e as dynamic; // replace e with anonymous definition /* * Console.WriteLine($"New contact(s) added: {e.FirstName} {e.LastName} {e.Age}."); */ } // Contacts_ContactedAdded } // Program Class