CSharp examples for Custom Type:Event
Add event to a class
using static System.Console; using System;// w ww .j a v a 2 s . c o m using System.Collections.Generic; using System.Text.RegularExpressions; class Program { static void Main(string[] args) { var harry = new Person { Name = "Harry" }; var mary = new Person { Name = "Mary" }; var jill = new Person { Name = "Jill" }; harry.Shout += Harry_Shout; harry.Poke(); harry.Poke(); harry.Poke(); harry.Poke(); } private static void Harry_Shout(object sender, EventArgs e) { Person p = (Person)sender; WriteLine($"{p.Name} is this angry: {p.AngerLevel}."); } } public class Person : IComparable<Person> { public string Name; public DateTime DateOfBirth; public List<Person> Children = new List<Person>(); public int CompareTo(Person other) { return Name.CompareTo(other.Name); } public event EventHandler Shout; public int AngerLevel; public void Poke() { AngerLevel++; if (AngerLevel >= 3) { if (Shout != null) { Shout(this, EventArgs.Empty); } } } }