Home  >  Article  >  Backend Development  >  What are events in C#?

What are events in C#?

王林
王林forward
2023-09-14 16:41:031067browse

C# 中的事件是什么?

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# −

Example

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);
      }
   }
}

Output

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete