Skip to content

Instantly share code, notes, and snippets.

@bugshake
Created October 2, 2017 18:50
Show Gist options
  • Save bugshake/d4a6ea578f2f96f07c5c6c2d701141e6 to your computer and use it in GitHub Desktop.
Save bugshake/d4a6ea578f2f96f07c5c6c2d701141e6 to your computer and use it in GitHub Desktop.
C# Observable Property
// get an event when a property changes
public class ObservableProperty<T>
{
T value;
public delegate void ChangeEvent(T data);
public event ChangeEvent changed;
public ObservableProperty(T initialValue)
{
value = initialValue;
}
public void Set(T v)
{
if (!v.Equals(value))
{
value = v;
if (changed != null)
{
changed(value);
}
}
}
public T Get()
{
return value;
}
public static implicit operator T(ObservableProperty<T> p)
{
return p.value;
}
}
@bugshake
Copy link
Author

bugshake commented Oct 2, 2017

Example:

        var toggle = new ObservableProperty<bool>(false);
        toggle.changed += (b) => { print("A") };
        if (toggle) print("B");
        print("C");
        toggle.Set(true);
        print("D");
        toggle.Set(true);

Will output:

        CAD

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment