- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What are events in C#?
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
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!
Advertisements