19 November 2026

C# Delegates and Events for Beginners: A Student Score Alert

  Asp.Net CS By Example       19 November 2026

A delegate lets a variable hold a method with a matching input and output. An event lets an object announce that something happened. In this lesson, a score register announces a pass, and another method listens for that announcement.

How the notification travels

Record score → Check pass mark → Raise event → Call subscribers

Delegate first: store a rule

Func<int, bool> is a built-in delegate type. It describes a method that receives one integer and returns true or false. The lambda below is the method stored in the delegate.

Func<int, bool> isPass = score => score >= 40;
Console.WriteLine(isPass(78)); // True

This rule answers a question when you call it. An event is useful when an object needs to notify other code after an action.

Build a runnable event example

Install a supported .NET SDK, create a console project, and open Program.cs. Replace its contents with the complete example below.

dotnet new console -n StudentScoreEvents
cd StudentScoreEvents
Func<int, bool> isPass = score => score >= 40;
Console.WriteLine($"Delegate: score 78 passes = {isPass(78)}");

var register = new ScoreRegister();
register.PassRecorded += ShowPass;

register.Record("Asha", 78);
register.Record("Ravi", 35);

register.PassRecorded -= ShowPass;
register.Record("Mina", 90);

static void ShowPass(object? sender, ScoreEventArgs e)
{
    Console.WriteLine($"Event: {e.Name} passed with {e.Score}");
}

public sealed class ScoreRegister
{
    public event EventHandler<ScoreEventArgs>? PassRecorded;

    public void Record(string name, int score)
    {
        if (score is < 0 or > 100)
            throw new ArgumentOutOfRangeException(nameof(score));

        Console.WriteLine($"Recorded: {name} = {score}");
        if (score >= 40)
            PassRecorded?.Invoke(this, new ScoreEventArgs(name, score));
    }
}

public sealed class ScoreEventArgs(string name, int score) : EventArgs
{
    public string Name { get; } = name;
    public int Score { get; } = score;
}

Save Program.cs, then run dotnet run.

Expected output

Delegate: score 78 passes = True
Recorded: Asha = 78
Event: Asha passed with 78
Recorded: Ravi = 35
Recorded: Mina = 90

Asha's passing score triggers the event. Ravi's score is recorded but does not pass. Mina passes after the handler has been removed, so there is no event message for Mina.

Understand each important line

  • event EventHandler<ScoreEventArgs>? declares a notification with a sender and data object. The question mark allows zero subscribers.
  • += ShowPass subscribes the method. A matching -= ShowPass unsubscribes it.
  • PassRecorded?.Invoke(...) raises the event only when a handler exists. Only ScoreRegister raises its own event.
  • ScoreEventArgs carries the student name and score to listeners.

When to use which: Pass a delegate when a method needs a rule or callback, such as a comparison or calculation. Use an event when an object announces a change and other objects may subscribe. A long-lived publisher can keep subscribed objects alive, so remove handlers when they are no longer needed.

Practice

  1. Change the pass mark from 40 to 50. Predict which event messages appear before running.
  2. Add a second named handler that prints Certificate ready for Asha. Subscribe it before recording Asha.
  3. Try a score of 110. Explain why the exception happens before the event.

Quick check: Why cannot outside code call register.PassRecorded(...) directly? Because an event exposes subscription to callers; the publisher controls when it is raised.

Continue with the C# tutorial path. For the language rules, see Microsoft's delegate guide and event guide.

logoblog

Thanks for reading C# Delegates and Events for Beginners: A Student Score Alert

Previous
« Prev Post

No comments:

Post a Comment

Please do not enter any spam link in the comment box.