Search⌘ K
AI Features

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 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.

C# 14.0
namespace Delegates;
public class FootballMatch
{
public string Team1 { get; private set; }
public string Team2 { get; private set; }
public int Team1Score { get; private set; }
public int Team2Score { get; private set; }
public FootballMatch(string team1, string team2)
{
Team1 = team1;
Team2 = team2;
}
public void IncreaseTeam1Score()
{
Team1Score++;
}
public void IncreaseTeam2Score()
{
Team2Score++;
}
}
  • 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. ...