Skip to content

Instantly share code, notes, and snippets.

@karenpayneoregon
Created June 6, 2024 11:15
Show Gist options
  • Save karenpayneoregon/5b91525bf761f125aeb952f9610e5049 to your computer and use it in GitHub Desktop.
Save karenpayneoregon/5b91525bf761f125aeb952f9610e5049 to your computer and use it in GitHub Desktop.
Provides three different way to provide change notification

Several ways to implement change notification done with NET8. There are indeed other ways to provide change notification, these are the basics.

CustomerFody.cs requres two NuGet package

Add FodyWeavers.xml to the root of the project and set to copy if newer.

<?xml version="1.0" encoding="utf-8"?>
<Weavers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="FodyWeavers.xsd">
  <PropertyChanged />
</Weavers>
public class Customer : INotifyPropertyChanged
{
private string _firstName;
private string _lastName;
private DateOnly _birthDate;
public string FirstName
{
get => _firstName;
set
{
if (value == _firstName) return;
_firstName = value;
OnPropertyChanged();
}
}
public string LastName
{
get => _lastName;
set
{
if (value == _lastName) return;
_lastName = value;
OnPropertyChanged();
}
}
public DateOnly BirthDate
{
get => _birthDate;
set
{
if (value.Equals(_birthDate)) return;
_birthDate = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class Customer : INotifyPropertyChanged
{
private string _firstName;
private string _lastName;
private DateOnly _birthDate;
public string FirstName { get => _firstName; set => SetField(ref _firstName, value); }
public string LastName { get => _lastName; set => SetField(ref _lastName, value); }
public DateOnly BirthDate { get => _birthDate; set => SetField(ref _birthDate, value); }
public override string ToString() => $"{FirstName} {LastName}";
public event PropertyChangedEventHandler? PropertyChanged;
protected void OnPropertyChanged(string propertyName)
=> PropertyChanged?.Invoke(this, new(propertyName));
protected bool SetField<T>(ref T field, T value, [CallerMemberName] string propertyName = "")
{
if (EqualityComparer<T>.Default.Equals(field, value)) return false;
field = value;
OnPropertyChanged(propertyName);
return true;
}
}
public class Customer : INotifyPropertyChanged
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateOnly BirthDate { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
private void OnLastNameChanged()
{
if (LastName == "Doe")
{
// TODO
}
}
protected void OnPropertyChanged(string propertyName, object before, object after)
{
if (propertyName == nameof(FirstName) && (string)after == "Mary")
{
// TODO
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment