Skip to content
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

Add events section to Expression-bodied members article #41868

Merged
merged 3 commits into from
Aug 1, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,14 @@ You can use expression body definitions to implement property `get` and `set` ac

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

## Events

Similarly, event `add` and `remove` accessors may be expression-bodied:
BillWagner marked this conversation as resolved.
Show resolved Hide resolved

[!code-csharp[expression-bodied-event-add-remove](../../../../samples/snippets/csharp/programming-guide/classes-and-structs/ExpressionBodiedMembers/expr-bodied-event.cs#1)]

For more information about events, see [Events (C# Programming Guide)](../events/index.md).

## Constructors

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.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
using System;

namespace ExprBodied;

// <Snippet1>
public class ChangedEventArgs : EventArgs
{
public required int NewValue { get; init; }
}

public class ObservableNum(int _value)
{
public event EventHandler<ChangedEventArgs> ChangedGeneric = default!;

public event EventHandler Changed
{
// Note that, while this is syntactically valid, it won't work as expected because it's creating a new delegate object with each call.
add => ChangedGeneric += (sender, args) => value(sender, args);
remove => ChangedGeneric -= (sender, args) => value(sender, args);
}

public int Value
{
get => _value;
set => ChangedGeneric?.Invoke(this, new() { NewValue = (_value = value) });
}
}
// </Snippet1>

public class Example
BillWagner marked this conversation as resolved.
Show resolved Hide resolved
{
public static void Main()
{
void PrintingHandler(object? sender, object? args)
=> Console.WriteLine((args as ChangedEventArgs)?.NewValue);
ObservableNum num = new(2);
num.Changed += PrintingHandler;
num.Value = 3;
num.Changed -= PrintingHandler;
num.Value = 1; // Still prints!
}
}
Loading