public class Calculator { public delegate void CalculationHandler(object sender, MethodReturnEventArgs e); public event CalculationHandler CalculationCompleted; public void AddNumbers(int num1, int num2) { int result = num1 + num2; MethodReturnEventArgs args = new MethodReturnEventArgs(result); CalculationCompleted?.Invoke(this, args); } } public static void Main(string[] args) { Calculator c = new Calculator(); c.CalculationCompleted += Calculator_CalculationCompleted; c.AddNumbers(5, 10); } private static void Calculator_CalculationCompleted(object sender, MethodReturnEventArgs e) { Console.WriteLine($"Calculation result: {e.Result}"); }
public class DatabaseConnection { public delegate void ConnectionHandler(object sender, MethodReturnEventArgs e); public event ConnectionHandler ConnectionStatus; public bool Connect(string connectionString) { bool success = true; // code to establish database connection if (success) { MethodReturnEventArgs args = new MethodReturnEventArgs("Connected"); ConnectionStatus?.Invoke(this, args); } else { MethodReturnEventArgs args = new MethodReturnEventArgs("Failed"); ConnectionStatus?.Invoke(this, args); } return success; } } public static void Main(string[] args) { DatabaseConnection db = new DatabaseConnection(); db.ConnectionStatus += DatabaseConnection_ConnectionStatus; bool isConnected = db.Connect("myConnectionString"); } private static void DatabaseConnection_ConnectionStatus(object sender, MethodReturnEventArgs e) { Console.WriteLine($"Connection status: {e.Result}"); }In this example, we create a class called DatabaseConnection that has an event called ConnectionStatus. We use MethodReturnEventArgs to pass the status of the connection back to the caller method. In the Main method, we create an instance of DatabaseConnection, subscribe to the ConnectionStatus event, and call the Connect method. When the connection is established, the event handler method DatabaseConnection_ConnectionStatus is called and the status is printed to the console. Package Library: Microsoft.VisualStudio.Shell.Interop.8.0