Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

event: practical reference

event: practical reference: event exposes controlled delegate subscription, but only its declaring type can invoke it.

Version: C# language; verified against C# 14 reference

Syntax

event /* grammar-specific form */

event exposes controlled delegate subscription, but only its declaring type can invoke it.

Use it for one-to-many notifications with an explicit unsubscribe lifecycle.

A subscription keeps the receiver alive, and a handler exception stops the multicast.

Only a field-like event has a compiler-generated delegate backing field that is null without subscribers; custom add/remove accessors need not store a delegate field at all. Concurrent publication needs a safe snapshot.

The complete program actually uses event; its exact expected stdout is changed.

Examples

using System;
using System.Buffers;
using System.Collections.Concurrent;
using System.Collections.Frozen;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using Number = System.Int32;

var source = new Source(); source.Changed += () => Console.WriteLine("changed"); source.Raise();
sealed class Source { public event Action? Changed; public void Raise() => Changed?.Invoke(); }

Result

changed

The complete program actually uses `event`; its exact expected stdout is `changed`.

Sources