Delegates (Continued)
Explore the practical use of delegates in C# for decoupling code and managing notifications in applications like a football match simulation. Learn why delegates improve flexibility over direct method calls, understand exposure risks, and see how events provide safer encapsulation for subscriber management.
We'll cover the following...
We have focused on syntax so far, but we must also understand the practical applications. Developers often ask why delegates are necessary when methods can be called directly.
Delegates are essential for decoupling code. Suppose we have a class that represents a football game. It tracks the events of the game and updates its state accordingly. For simplicity, our FootballMatch class only tracks the scores.
The following code defines a basic class to hold match state.
Line 1: We use a file-scoped namespace to organize the code.
Lines 5–6: We define properties to store the team names.
Lines 8–9: We define properties to store the team scores.
Lines 11–15: We initialize the match with the names of the two teams in the constructor. ...