What are events in C#?

CsharpProgrammingServer Side Programming

Events are user actions such as key press, clicks, mouse movements, etc., or some occurrence such as system-generated notifications.

The events are declared and raised in a class and associated with the event handlers using delegates within the same class or some other class. The class containing the event is used to publish the event.

To declare an event inside a class, first a delegate type for the event must be declared. For example,

public delegate string myDelegate(string str);

Now, declare an event −

event myDelegate newEvent;

Now let us see an example to work with events in C# −

Example

 Live 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!
raja
Published on 08-Aug-2018 09:55:59
Advertisements