Skip to content

Instantly share code, notes, and snippets.

@JokerMartini
Last active July 5, 2017 14:15
Show Gist options
  • Save JokerMartini/c3fad7fa78296a50f4d7 to your computer and use it in GitHub Desktop.
Save JokerMartini/c3fad7fa78296a50f4d7 to your computer and use it in GitHub Desktop.
C# Base class for observable objects.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace NotifyExample
{
public abstract class NotifyBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged([CallerMemberName] string propertyName = null)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
protected bool Set<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(field, value)) return false;
field = value;
RaisePropertyChanged(propertyName);
return true;
}
}
public class props : NotifyBase
{
// USAGE EXAMPLES
private string name;
public string Name
{
get { return name; }
set { Set(ref name, value); }
}
private string height;
public string Height
{
get { return height; }
set
{
Set(ref height, value);
// instead of writing it like this... RaisePropertyChanged("Name");
RaisePropertyChanged(nameof(Name)); // at compile time this changes to "Name"
}
}
private List<string> nameList;
public List<string> NameList
{
get { return nameList ?? (nameList = new List<string>()); }
set
{
Set(ref nameList, value);
RaisePropertyChanged("Name");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment