Events are user actions such as key presses, clicks, mouse movements, etc., or certain events such as system-generated notifications.
Events are declared and raised in a class with event handlers using delegates in the same class or other classes. The class containing the event is used to publish the event.
To declare an event in a class, you must first declare the delegate type of the event. For example,
public delegate string myDelegate(string str);
Now, declare an event −
event myDelegate newEvent;
Now let’s see an example of handling events in C# −
Online Demo
using System; namespace Demo { public delegate string myDelegate(string str); class EventProgram { event myDelegate newEvent; public EventProgram() { this.newEvent += new myDelegate(this.WelcomeUser); } public string WelcomeUser(string username) { return "Welcome " + username; } static void Main(string[] args) { EventProgram obj1 = new EventProgram(); string result = obj1.newEvent("My Website!"); Console.WriteLine(result); } } }
Welcome My Website!
The above is the detailed content of What are events in C#?. For more information, please follow other related articles on the PHP Chinese website!