Temas importantes de C#

Events

Events implement a type-safe publisher/subscriber relationship.

How it works

Publish notifications without exposing delegate invocation.

Subscribers can add and remove handlers, but only the declaring class can raise the event.

Runnable C# example

C#
Run code →
Program.cs
using System;

class Counter
{
    public event EventHandler? ThresholdReached;
    public void ReachThreshold() => ThresholdReached?.Invoke(this, EventArgs.Empty);
}

class Program
{
    static void Main()
    {
        var counter = new Counter();
        counter.ThresholdReached += (_, _) => Console.WriteLine("Threshold reached");
        counter.ReachThreshold();
    }
}
Expected output
Threshold reached

Practice with the debugger

Set a breakpoint on an important assignment or condition, click Debug, and inspect the local values before stepping to the next line.