Skip to content

Instantly share code, notes, and snippets.

@wolf99
Created May 31, 2017 10:26
Show Gist options
  • Save wolf99/c6aa68d67be855735d256dcca0ae543d to your computer and use it in GitHub Desktop.
Save wolf99/c6aa68d67be855735d256dcca0ae543d to your computer and use it in GitHub Desktop.
A boilerplate C# implementation of INotifyPropertyChanged
using System;
using System.ComponentModel; // For INotifyPropertyChanged interface
using System.Runtime.CompilerServices; // For CallerMemberName, could use nameof() otherwise
namespace FooProgram
{
public class BoilerplateNotify : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
// Adapted from https://stackoverflow.com/a/36972187/1292918
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private bool _demoProperty1 = false;
public bool DemoProperty1
{
get => _demoProperty;
set { _demoProperty = value; OnPropertyChanged(); }
}
// To use only one line for simple properties add the following
// Adapted from https://stackoverflow.com/a/1316417/1292918
protected bool SetField<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
{
//if (EqualityComparer<T>.Default.Equals(filed, value)) return false;
// or
if (field.Equals(value) return false;
field = value;
OnPropertyChanged(propertyName);
return true;
}
private string _demoProperty2;
public string DemoProperty2
{
get => _demoProperty;
set => SetField(ref _demoProperty2, value);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment