Skip to content

Add information about partial events & ctors #45336

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Mar 14, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions docfx.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,8 @@
"field-keyword.md",
"unbound-generic-types-in-nameof.md",
"first-class-span-types.md",
"simple-lambda-parameters-with-modifiers.md"
"simple-lambda-parameters-with-modifiers.md",
"partial-events-and-constructors.md"
],
"src": "_csharplang/proposals",
"dest": "csharp/language-reference/proposals",
Expand Down Expand Up @@ -508,7 +509,7 @@
"_csharplang/proposals/csharp-11.0/*.md": "09/30/2022",
"_csharplang/proposals/csharp-12.0/*.md": "08/15/2023",
"_csharplang/proposals/csharp-13.0/*.md": "10/31/2024",
"_csharplang/proposals/*.md": "02/14/2025",
"_csharplang/proposals/*.md": "03/11/2025",
"_roslyn/docs/compilers/CSharp/Compiler Breaking Changes - DotNet 7.md": "11/08/2022",
"_roslyn/docs/compilers/CSharp/Compiler Breaking Changes - DotNet 8.md": "11/08/2023",
"_roslyn/docs/compilers/CSharp/Compiler Breaking Changes - DotNet 9.md": "11/09/2024",
Expand Down Expand Up @@ -686,7 +687,8 @@
"_csharplang/proposals/field-keyword.md": "The `field` contextual keyword",
"_csharplang/proposals/unbound-generic-types-in-nameof.md": "Unbound generic types in `nameof`",
"_csharplang/proposals/first-class-span-types.md": "First-class span types",
"_csharplang/proposals/simple-lambda-parameters-with-modifiers.md": "Simple lambda parameters with modifiers",
"_csharplang/proposals/simple-lambda-parameters-with-modifiers.md": "Simple lambda parameters with modifiers",
"_csharplang/proposals/partial-events-and-constructors.md": "Partial events and constructors",
"_roslyn/docs/compilers/CSharp/Compiler Breaking Changes - DotNet 7.md": "C# compiler breaking changes since C# 10",
"_roslyn/docs/compilers/CSharp/Compiler Breaking Changes - DotNet 8.md": "C# compiler breaking changes since C# 11",
"_roslyn/docs/compilers/CSharp/Compiler Breaking Changes - DotNet 9.md": "C# compiler breaking changes since C# 12",
Expand Down Expand Up @@ -811,6 +813,7 @@
"_csharplang/proposals/unbound-generic-types-in-nameof.md": "This proposal introduces the ability to use unbound generic types such as `List<>` in `nameof` expressions. The type argument isn't required.",
"_csharplang/proposals/first-class-span-types.md": "This proposal provides several implicit conversions to `Span<T>` and `ReadOnlySpan<T>` that enable library authors to have fewer overloads and developers to write code that resolves to faster Span based APIs",
"_csharplang/proposals/simple-lambda-parameters-with-modifiers.md": "This proposal provides allows lambda parmaeters to be declared with modifiers without requiring their type names. You can add modifiers like `ref` and `out` to lambda parameters without specifying their type.",
"_csharplang/proposals/partial-events-and-constructors.md": "This proposal provides allows partial events and constructors to be declared in partial classes. This allows the event and constructor to be split across class declarations.",
"_roslyn/docs/compilers/CSharp/Compiler Breaking Changes - DotNet 7.md": "Learn about any breaking changes since the initial release of C# 10 and included in C# 11",
"_roslyn/docs/compilers/CSharp/Compiler Breaking Changes - DotNet 8.md": "Learn about any breaking changes since the initial release of C# 11 and included in C# 12",
"_roslyn/docs/compilers/CSharp/Compiler Breaking Changes - DotNet 9.md": "Learn about any breaking changes since the initial release of C# 12 and included in C# 13",
Expand Down
15 changes: 7 additions & 8 deletions docs/csharp/event-pattern.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@ void EventRaised(object sender, EventArgs args);

This standard signature provides insight into when events are used:

- ***The return type is void***. Events may have zero to many listeners. Raising an event notifies all listeners. In general, listeners don't provide values in response to events.
- ***The return type is void***. Events can have zero to many listeners. Raising an event notifies all listeners. In general, listeners don't provide values in response to events.
- ***Events indicate the sender***: The event signature includes the object that raised the event. That provides any listener with a mechanism to communicate with the sender. The compile-time type of `sender` is `System.Object`, even though you likely know a more derived type that would always be correct. By convention, use `object`.
- ***Events package additional information in a single structure***: The `args` parameter is a type derived from <xref:System.EventArgs?displayProperty=nameWithType> that includes any additional necessary information. (You'll see in the [next section](modern-events.md) that this convention is no longer enforced.) If your event type doesn't need any more arguments, you still must provide both arguments. There's a special value, <xref:System.EventArgs.Empty?displayProperty=nameWithType> that you should use to denote that your event doesn't contain any additional information.
- ***Events package more information in a single structure***: The `args` parameter is a type derived from <xref:System.EventArgs?displayProperty=nameWithType> that includes any more necessary information. (You'll see in the [next section](modern-events.md) that this convention is no longer enforced.) If your event type doesn't need any more arguments, you still must provide both arguments. There's a special value, <xref:System.EventArgs.Empty?displayProperty=nameWithType> that you should use to denote that your event doesn't contain any additional information.

Let's build a class that lists files in a directory, or any of its subdirectories that follow a pattern. This component raises an event for each file found that matches the pattern.

Expand All @@ -48,22 +48,21 @@ The simplest way to add an event to your class is to declare that event as a pub

:::code language="csharp" source="./snippets/events/Program.cs" id="DeclareEvent":::

This looks like it's declaring a public field, which would appear to be a bad object-oriented practice. You want to protect data access through properties, or methods. While this code might look like a bad practice, the code generated by the compiler does create wrappers so that the event objects can only be accessed in safe ways. The only operations available on a field-like event are *add handler*:
This looks like it's declaring a public field, which would appear to be a bad object-oriented practice. You want to protect data access through properties, or methods. While this code might look like a bad practice, the code generated by the compiler does create wrappers so that the event objects can only be accessed in safe ways. The only operations available on a field-like event are *add* and *remove* handler:

:::code language="csharp" source="./snippets/events/Program.cs" id="AttachEventHandler":::

And *remove handler*:

:::code language="csharp" source="./snippets/events/Program.cs" id="DetachHandler":::

There's a local variable for the handler. If you used the body of the lambda, the remove wouldn't work correctly. It would be a different instance of the delegate, and silently do nothing.
There's a local variable for the handler. If you used the body of the lambda, the `remove` handler wouldn't work correctly. It would be a different instance of the delegate, and silently do nothing.

Code outside the class can't raise the event, nor can it perform any other operations.

Beginning with C# 14, events can be declared as [partial members](./language-reference/keywords/partial-member.md). A partial event declaration must include a *defining declaration* and an *implementing declaration*. The defining declaration must use the field-like event syntax. The implementing declaration must declare the `add` and `remove` handlers.

## Return values from event subscribers

Your simple version is working fine. Let's add another feature:
Cancellation.
Your simple version is working fine. Let's add another feature: Cancellation.

When you raise the *Found* event, listeners should be able to stop further processing, if this file is the last one sought.

Expand Down
23 changes: 10 additions & 13 deletions docs/csharp/language-reference/keywords/add.md
Original file line number Diff line number Diff line change
@@ -1,25 +1,22 @@
---
description: Learn how to create custom event accessors using add keyword in C#
title: "add keyword"
ms.date: 07/20/2015
description: The `add` contextual keyword declares an event accessor that adds a handler to that event.
title: "The `add` keyword"
ms.date: 03/13/2025
f1_keywords:
- "add_CSharpKeyword"
helpviewer_keywords:
- "add event accessor [C#]"
ms.assetid: faf30b99-10e8-45cd-ab9a-57585d4d1d8d
---
# add (C# Reference)
# The `add` contextual keyword (C# Reference)

The `add` contextual keyword is used to define a custom event accessor that is invoked when client code subscribes to your [event](./event.md). If you supply a custom `add` accessor, you must also supply a [remove](./remove.md) accessor.

## Example
The `add` contextual keyword is used to define a custom event accessor that is invoked when client code subscribes to your [event](./event.md). If you supply a custom `add` accessor, you must also supply a [remove](./remove.md) accessor.

The following example shows an event that has custom `add` and [remove](./remove.md) accessors. For the full example, see [How to implement interface events](../../programming-guide/events/how-to-implement-interface-events.md).
[!code-csharp[csrefKeywordsContextual#15](~/samples/snippets/csharp/VS_Snippets_VBCSharp/csrefKeywordsContextual/CS/csrefKeywordsContextual.cs#15)]
You do not typically need to provide your own custom event accessors. The accessors that are automatically generated by the compiler when you declare an event are sufficient for most scenarios.

:::code language="csharp" source="./snippets/events.cs" id="AddHandler":::

You don't typically need to provide your own custom event accessors. The automatically generated accessors when you declare an event are sufficient for most scenarios. Beginning with C# 14, you can declare [`partial`](./partial-member.md) events. The implementing declaration of a partial event must declare the `add` and `remove` handlers.

## See also

- [Events](../../programming-guide/events/index.md)
35 changes: 17 additions & 18 deletions docs/csharp/language-reference/keywords/event.md
Original file line number Diff line number Diff line change
@@ -1,44 +1,43 @@
---
description: "event - C# Reference"
title: "event keyword"
ms.date: 07/20/2015
description: "Learn how to declare events with the `event` keyword - C# Reference"
title: "The `event` keyword"
ms.date: 03/13/2025
f1_keywords:
- "event"
- "remove"
- "event_CSharpKeyword"
- "add"
helpviewer_keywords:
- "event keyword [C#]"
ms.assetid: 7858fd85-153b-4259-85d0-6aa13c35f174
---
# event (C# reference)
# The `event` keyword (C# reference)

An ***event*** is a member that enables an object to trigger notifications. Event users can attach executable code for events by supplying ***event handlers***. The `event` keyword declares an ***event***. The event is of a delegate type. While an object triggers an event, the event invokes all supplied event handlers. Event handlers are delegate instances added to the event and executed when the event is raised. Event users can add or remove their event handlers on an event.

## Example
The following example shows how to declare and raise an event that uses <xref:System.EventHandler> as the underlying delegate type. For the complete code example, see [How to publish events that conform to .NET Guidelines](/dotnet/standard/events). That sample demonstrates the generic <xref:System.EventHandler%601> delegate type, how to subscribe to an event, and create an event handler method,

The following example shows how to declare and raise an event that uses <xref:System.EventHandler> as the underlying delegate type. For the complete code example that also shows how to use the generic <xref:System.EventHandler%601> delegate type and how to subscribe to an event and create an event handler method, see [How to publish events that conform to .NET Guidelines](/dotnet/standard/events).
:::code language="csharp" source="./snippets/Events.cs" id="EventExample":::

[!code-csharp[csrefKeywordsModifiers#7](~/samples/snippets/csharp/VS_Snippets_VBCSharp/csrefKeywordsModifiers/CS/csrefKeywordsModifiers.cs#7)]
Events are multicast delegates that can only be invoked from within the class (or derived classes) or struct where they're declared (the publisher class). If other classes or structs subscribe to the event, their event handler methods are called when the publisher class raises the event. For more information and code examples, see [Events](../../programming-guide/events/index.md) and [Delegates](../../programming-guide/delegates/index.md).

Events are a special kind of multicast delegate that can only be invoked from within the class (or derived classes) or struct where they are declared (the publisher class). If other classes or structs subscribe to the event, their event handler methods will be called when the publisher class raises the event. For more information and code examples, see [Events](../../programming-guide/events/index.md) and [Delegates](../../programming-guide/delegates/index.md).
Events can be marked as [`public`](./public.md), [`private`](./private.md), [`protected`](./protected.md), [`internal`](./internal.md), [`protected internal`](./protected-internal.md), or [`private protected`](./private-protected.md). These access modifiers define how users of the class can access the event. For more information, see [Access Modifiers](../../programming-guide/classes-and-structs/access-modifiers.md).

Events can be marked as [public](./public.md), [private](./private.md), [protected](./protected.md), [internal](./internal.md), [protected internal](./protected-internal.md), or [private protected](./private-protected.md). These access modifiers define how users of the class can access the event. For more information, see [Access Modifiers](../../programming-guide/classes-and-structs/access-modifiers.md).
Beginning with C# 14, events can be [`partial`](./partial-member.md). Partial events have one defining declaration and one implementing declaration. The defining declaration must use the field-like syntax. The implementing declaration must declare the `add` and `remove` handlers.

## Keywords and events

The following keywords apply to events.

|Keyword|Description|For more information|
|-------------|-----------------|--------------------------|
|[static](./static.md)|Makes the event available to callers at any time, even if no instance of the class exists.|[Static Classes and Static Class Members](../../programming-guide/classes-and-structs/static-classes-and-static-class-members.md)|
|[virtual](./virtual.md)|Allows derived classes to override the event behavior by using the [override](./override.md) keyword.|[Inheritance](../../fundamentals/object-oriented/inheritance.md)|
|[sealed](./sealed.md)|Specifies that for derived classes it is no longer virtual.||
|[abstract](./abstract.md)|The compiler will not generate the `add` and `remove` event accessor blocks and therefore derived classes must provide their own implementation.||
| Keyword | Description | For more information |
|---------------------------|-----------------|----------------------|
| [`static`](./static.md) | Makes the event available to callers at any time, even if no instance of the class exists. | [Static Classes and Static Class Members](../../programming-guide/classes-and-structs/static-classes-and-static-class-members.md) |
| [`virtual`](./virtual.md) | Allows derived classes to override the event behavior by using the [override](./override.md) keyword. | [Inheritance](../../fundamentals/object-oriented/inheritance.md)|
| [`sealed`](./sealed.md) | Specifies that for derived classes it's no longer virtual. | |
| [`abstract`](./abstract.md) | The compiler doesn't generate the `add` and `remove` event accessor blocks and therefore derived classes must provide their own implementation. | |

An event may be declared as a static event by using the [static](./static.md) keyword. This makes the event available to callers at any time, even if no instance of the class exists. For more information, see [Static Classes and Static Class Members](../../programming-guide/classes-and-structs/static-classes-and-static-class-members.md).
An event can be declared as a static event by using the [static](./static.md) keyword. Static events are available to callers at any time, even if no instance of the class exists. For more information, see [Static Classes and Static Class Members](../../programming-guide/classes-and-structs/static-classes-and-static-class-members.md).

An event can be marked as a virtual event by using the [virtual](./virtual.md) keyword. This enables derived classes to override the event behavior by using the [override](./override.md) keyword. For more information, see [Inheritance](../../fundamentals/object-oriented/inheritance.md). An event overriding a virtual event can also be [sealed](./sealed.md), which specifies that for derived classes it is no longer virtual. Lastly, an event can be declared [abstract](./abstract.md), which means that the compiler will not generate the `add` and `remove` event accessor blocks. Therefore derived classes must provide their own implementation.
An event can be marked as a virtual event by using the [`virtual`](./virtual.md) keyword. Derived classes can override the event behavior by using the [`override`](./override.md) keyword. For more information, see [Inheritance](../../fundamentals/object-oriented/inheritance.md). An event overriding a virtual event can also be [`sealed`](./sealed.md), which specifies that for derived classes it's no longer virtual. Lastly, an event can be declared [`abstract`](./abstract.md), which means that the compiler doesn't generate the `add` and `remove` event accessor blocks. Therefore derived classes must provide their own implementation.

## C# language specification

Expand Down
Loading