Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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