Skip to content

Instantly share code, notes, and snippets.

@Quickz
Created March 3, 2020 18:50
Show Gist options
  • Save Quickz/af33151ecd419030d606e2c5e0909916 to your computer and use it in GitHub Desktop.
Save Quickz/af33151ecd419030d606e2c5e0909916 to your computer and use it in GitHub Desktop.
A generic variable wrapper that allows detecting value changes.
using System;
namespace VariableChangedEventPattern
{
class Program
{
private static void Main()
{
Game.Score.Changed += OnScoreChanged;
Game.Score.Value += 200;
Game.Score.Value += 50;
Console.ReadKey();
}
private static void OnScoreChanged(object sender, ChangedEventArgs<int> e)
{
Console.WriteLine($"Score changed to {e.NewValue}!");
}
}
static class Game
{
public static Changing<int> Score { get; private set; } = new Changing<int>();
}
class ChangedEventArgs<T> : EventArgs
{
public T OldValue { get; private set; }
public T NewValue { get; private set; }
public ChangedEventArgs(T oldValue, T newValue)
{
OldValue = oldValue;
NewValue = newValue;
}
}
class Changing<T>
{
public event EventHandler<ChangedEventArgs<T>> Changed;
public T Value
{
get
{
return _value;
}
set
{
T oldValue = _value;
_value = value;
Changed?.Invoke(null, new ChangedEventArgs<T>(oldValue, _value));
}
}
private T _value;
public Changing(T value = default)
{
Value = value;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment