Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

remove: practical reference

remove: practical reference: remove defines an event unsubscription accessor and receives the handler as value.

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

Syntax

remove /* grammar-specific form */

remove defines an event unsubscription accessor and receives the handler as value.

Use it with add when subscription storage requires custom control.

Asymmetry between add and remove causes leaks or ineffective unsubscribe operations.

Removing an absent handler should have deliberately defined behavior.

The complete program actually uses remove; its exact expected stdout is done.

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

Result

done

The complete program actually uses `remove`; its exact expected stdout is `done`.

Sources