using System.ComponentModel;
using System.Threading.Tasks;
public static async Task Main()
foo.CancelPropertyChanging += Foo_CancelPropertyChanging;
foo.Bar = "Hello World 2";
Console.WriteLine(foo.Bar);
Console.WriteLine(foo.Bar == "Hello World 2" ? "Error" : "Correct");
var fooAsync = new Foo();
fooAsync.Bar = "Init Value";
fooAsync.CancelPropertyChanging += Foo_AsyncCancelPropertyChanging;
fooAsync.Bar = "Hello World";
fooAsync.Bar = "Hello World 2";
Console.WriteLine(fooAsync.Bar);
Console.WriteLine(fooAsync.Bar == "Hello World 2" ? "Error" : "Correct");
void Foo_CancelPropertyChanging(object? sender, CancelPropertyChangingEventArgs e)
Console.WriteLine($"Changing Sync - OldValue: {e.OldValue} | NewValue: {e.NewValue}");
if (Convert.ToString(e.NewValue) == "Hello World 2")
e.Cancel = e.Cancel || true;
async void Foo_AsyncCancelPropertyChanging(object? sender, CancelPropertyChangingEventArgs e)
Console.WriteLine($"Changing Async - OldValue: {e.OldValue} | NewValue: {e.NewValue}");
if (Convert.ToString(e.NewValue) == "Hello World 2")
e.Cancel = e.Cancel || true;
public event EventHandler<CancelPropertyChangingEventArgs>? CancelPropertyChanging;
if (CancelPropertyChanging is { } cancelPropertyChanging)
var eventArgs = new CancelPropertyChangingEventArgs()
PropertyName = nameof(Bar),
cancelPropertyChanging(this, eventArgs);
public override string ToString() => Bar ?? "";
public class CancelPropertyChangingEventArgs : CancelEventArgs
public object? OldValue { get; set; }
public object? NewValue { get; set; }
public string PropertyName { get; set; } = "";