I was reading how to write events for your custom classes so after reading a little I thought give it a shot and created this sample code. Below code is using Product class with event and delegate for event handling and other class named Test is using this class and manipulate product class data. If you change the Name of the product event will fire.
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
61
62
63
64
65
66
67
68
69
70
71
72
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
/// <summary>
/// Product Class
/// </summary>
public class Product
{
public delegate void NameChangeEventHandler(int a);
public event NameChangeEventHandler NameChanged;
private string _name;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
if (NameChanged != null)
{
NameChanged(5);
}
}
}
public Product(string name)
{
Name = name;
}
public void PrintName()
{
Console.WriteLine("ProductName={0}", Name);
}
}
/// <summary>
/// Test Class
/// </summary>
public class Test
{
public void ChangeDetected(int a)
{
Console.WriteLine("change found,argument passed is {0}",a);
}
public void TestProduct()
{
Product p = new Product("najam awan");
p.PrintName();
p.NameChanged += ChangeDetected;
p.Name = "najaf";
p.PrintName();
Console.ReadKey();
}
}
static void Main(string[] args)
{
Test t = new Test();
t.TestProduct();
}
}
}
|