Home > Backend Development > C#.Net Tutorial > What are events in C#?

What are events in C#?

王林
Release: 2023-09-14 16:41:03
forward
1140 people have browsed it

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);
Copy after login

Now, declare an event −

event myDelegate newEvent;
Copy after login

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);
      }
   }
}
Copy after login

Output

Welcome My Website!
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template