Skip to content

EN CSharp Keyword event

Codex edited this page Oct 11, 2026 · 2 revisions

Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어

C#: event

Handbook C# · Practical Guide

Declare a message that external code subscribes to with += and unsubscribes with -=. The call usually belongs to the owner type.

Simple example (Example.cs)

Save this example separately as Example.cs. Run it independently of the other examples on this page.

Example.cs:

// PROJECT-EXAMPLE
var source = new Source();
source.Changed += () => System.Console.WriteLine("Changed");
source.Raise();
class Source { public event System.Action? Changed; public void Raise() => Changed?.Invoke(); }

Result:

Changed

Syntax

public event Action? Changed;

Example 1: simple form

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class Program
{
    public static async Task Main(string[] args)
    {
        Notifier source = new();
        Action<string> handler = text => Console.WriteLine(text);
        source.Message += handler; source.Publish("Ready");
        source.Message -= handler;
    }
}
public class Notifier { public event Action<string>? Message; public void Publish(string text) { Message?.Invoke(text); } }

Example 2: another practical form

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class Program
{
    public static async Task Main(string[] args)
    {
        Notifier source = new();
        Action handler = () => Console.WriteLine("Changed");
        source.Changed += handler; source.Publish(); source.Changed -= handler; source.Publish();
    }
}
public class Notifier { private Action? handlers; public event Action Changed { add { handlers += value; } remove { handlers -= value; } } public void Publish() { handlers?.Invoke(); } }

Official source: Microsoft Learn.

Clone this wiki locally