Skip to content

Commit 037ff93

Browse files
Add events section to Expression-bodied members article (#41868)
* Add events section to Expression-bodied members article * Update docs/csharp/programming-guide/statements-expressions-operators/expression-bodied-members.md --------- Co-authored-by: Bill Wagner <[email protected]>
1 parent 7efd5e3 commit 037ff93

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

docs/csharp/programming-guide/statements-expressions-operators/expression-bodied-members.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,14 @@ You can use expression body definitions to implement property `get` and `set` ac
5757

5858
For more information about properties, see [Properties (C# Programming Guide)](../classes-and-structs/properties.md).
5959

60+
## Events
61+
62+
Similarly, event `add` and `remove` accessors can be expression-bodied:
63+
64+
[!code-csharp[expression-bodied-event-add-remove](../../../../samples/snippets/csharp/programming-guide/classes-and-structs/ExpressionBodiedMembers/expr-bodied-event.cs#1)]
65+
66+
For more information about events, see [Events (C# Programming Guide)](../events/index.md).
67+
6068
## Constructors
6169

6270
An expression body definition for a constructor typically consists of a single assignment expression or a method call that handles the constructor's arguments or initializes instance state.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
using System;
2+
3+
namespace ExprBodied;
4+
5+
// <Snippet1>
6+
public class ChangedEventArgs : EventArgs
7+
{
8+
public required int NewValue { get; init; }
9+
}
10+
11+
public class ObservableNum(int _value)
12+
{
13+
public event EventHandler<ChangedEventArgs> ChangedGeneric = default!;
14+
15+
public event EventHandler Changed
16+
{
17+
// Note that, while this is syntactically valid, it won't work as expected because it's creating a new delegate object with each call.
18+
add => ChangedGeneric += (sender, args) => value(sender, args);
19+
remove => ChangedGeneric -= (sender, args) => value(sender, args);
20+
}
21+
22+
public int Value
23+
{
24+
get => _value;
25+
set => ChangedGeneric?.Invoke(this, new() { NewValue = (_value = value) });
26+
}
27+
}
28+
// </Snippet1>
29+
30+
public class ExpressionExample
31+
{
32+
public static void Main()
33+
{
34+
void PrintingHandler(object? sender, object? args)
35+
=> Console.WriteLine((args as ChangedEventArgs)?.NewValue);
36+
ObservableNum num = new(2);
37+
num.Changed += PrintingHandler;
38+
num.Value = 3;
39+
num.Changed -= PrintingHandler;
40+
num.Value = 1; // Still prints!
41+
}
42+
}

0 commit comments

Comments
 (0)