What 's the usefull of delegate and event in c# | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

What 's the usefull of delegate and event in c#

11th Jun 2017, 7:19 AM
HiChem Amrani
HiChem Amrani - avatar
2 Answers
+ 1
By events you can avoid checking the state of an object waiting something to change on it. Using them you register a listener for the event, and instead of hundreds of wasted checks you will get notified only when the event is triggered by the given object. Also, this makes scripting more easy in general: int score = 0; public void SpawnEnemy() { Enemy newEnemy = new Enemy(); newEnemy.Died += (e) => { score += 10; player.Tell("You killed " + e.Name + "! +10 points!"); } } Events are for notifier purposes. Delegates do declare signature. You can define an event the following way: public class Enemy { //. . . //the signature: public delegate void EnemyListener(Enemy e); //event using the signature: public event EnemyListener Died; //methods listening to this event //must have the given signature } You trigger it like that: public class Enemy { //. . . public void Hurt(int damage) { health -= damage; if (health <= 0) { if (Died != null) Died(this); } } } (The "if (Died != null)" checks if anyone listens to the event. If not, then by triggering the event a NullReferenceException whould be thrown, so always check != null before calling an event!) So, instead of this: interested --checks---> subject interested --checks---> subject interested --checks---> subject ... interested --checks---> subject - subject passes requirement interested does something You do: interested --registers--listener--> subject *later on* subject changes state subject triggers event ---> notify: interested interested does something
24th Jun 2017, 2:38 PM
Magyar Dávid
Magyar Dávid - avatar
0
wlh délégation mli7a l programmation mli7a lkolch
14th Aug 2018, 11:44 AM
talbi malek ben nabi
talbi malek ben nabi - avatar