Skip to content

Instantly share code, notes, and snippets.

@WillzZz
Last active August 4, 2016 17:48
Show Gist options
  • Save WillzZz/e188d3f42a9b87b20716 to your computer and use it in GitHub Desktop.
Save WillzZz/e188d3f42a9b87b20716 to your computer and use it in GitHub Desktop.
Bindable
using System;
public class Bindable<T>
{
private T _value;
public T Value
{
get { return _value; }
set
{
_value = value;
OnUpdated(value);
}
}
public Action<T> OnUpdated = delegate { };
public Bindable(T value)
{
Value = value;
}
public static explicit operator Bindable<T>(T t)
{
return new Bindable<T>(t);
}
public static implicit operator T(Bindable<T> bindable)
{
return bindable.Value;
}
}
@mr-robert
Copy link

ok while I said this was nice before, sadly it doesn't work. I'm just wondering did you test it?

The problem is that the
public static implicit operator Bindable(T t)
{
return new Bindable(t);
}

Always creates a new Bindable, so when you write the line:
myInt = 5;

this loses the old Bindable myInt, and is the equialent of writing
myInt = new Bindable(5);

so... the OnUpdated method of the original myint never gets called since it is now null and disposed and myInt is a whole new Bindable.

Really the way this needs to be written is something like this:

public class Bindable
{
private T _value;
public T Value
{
get { return _value; }
set
{
_value = value;
OnUpdated(value);
}
}

    public Action<T> OnUpdated = delegate { };


    public Bindable(T value)
    {
        Value = value;
    }

}

and set the value of everything using the now public value property.

@WillzZz
Copy link
Author

WillzZz commented Aug 26, 2015

Yup all of this is correct. Sorry I haven't updated this in a while. I've swapped to an explicit operator and letting Value be public. It's not possible to do an extension implicit operator in the current version of C#, although it could happen in the future. Ultimately that's what we want (We want a ref to the Bindable class and assign a value).

It's all syntactic sugar that I wanted, but couldn't quite achieve. I'll update the gist.

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