C# Events

Events in C# are common in UI applications like WebForms and WinForms. They can also be useful anywhere else, where you have a caller who may want to know when interesting things happen in your code.

To expose an event, you just need to define it in the class, and invoke it when something interesting happens. It's generally as easy as:

public class Foo
{
    public event EventHandler SomethingHappened;
    public void Go()
    {
        SomethingHappened?.Invoke(this, EventArgs.Empty);
    }
}

Foo foo = new();
foo.SomethingHappened += (sender, e) => Console.WriteLine("Something happened...");

View code on GitHub

Comments

Popular posts from this blog

C# Record Serialization

Versioned content in MVC

Add timestamp to photo using ImageMagick