-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevents.cs
60 lines (51 loc) · 1.62 KB
/
events.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
using System;
namespace EventDemo
{
// Step 1: Define a delegate
public delegate void SomeEventHandler(object sender, EventArgs e);
// Publisher class
class Publisher
{
// Step 2: Declare the event
public event SomeEventHandler SomeEvent;
// Method to raise the event
public void NotifyAboutEvent(EventArgs e)
{
// Step 3: Raise/Invoke the event
if (SomeEvent != null) // Check if there are any subscribers
{
SomeEvent(this, e); // Raise/Invoke the event
}
}
// Method to simulate an action that triggers the event
public void DoSomething()
{
Console.WriteLine("Publisher is doing something...");
// Raise the event when the action occurs
NotifyAboutEvent(EventArgs.Empty);
}
}
// Subscriber class
class Subscriber
{
// Event handler method
public void HandleSomeEvent(object sender, EventArgs e)
{
Console.WriteLine("Event received by Subscriber.");
}
}
class Program
{
static void Main(string[] args)
{
Publisher publisherObject = new();
Subscriber subscriberObject = new();
// subscriberObject subscribes to SomeEvent
// which is declared in publisherObject's class
// by using '+=' operator
publisherObject.SomeEvent += subscriberObject.HandleSomeEvent;
// Trigger the action to raise event in the publisher
publisherObject.DoSomething();
}
}
}