Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

add: practical reference

add: practical reference: add defines a custom event subscription accessor and receives the delegate as value.

Version: C# language and .NET 10 reference runtime

Syntax

add /* grammar-specific form */

add defines a custom event subscription accessor and receives the delegate as value.

Use it in an event when handler storage must be controlled.

The add and remove accessors must form a pair and preserve symmetry.

Concurrent subscriptions require atomic or locked management of the handler list.

The complete program actually uses add; its exact expected stdout is 3.

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 += value => Console.WriteLine(value); source.Raise(3);
sealed class Source { private Action<int>? changed; public event Action<int> Changed { add => changed += value; remove => changed -= value; } public void Raise(int value) => changed?.Invoke(value); }

Result

3

The complete program actually uses `add`; its exact expected stdout is `3`.

Sources