I have a class ListenableValue<T> that fires an event when the value is modified.
public class ListenableValue<T>
{
public delegate void OnChanged(T newValue);
public event OnChanged onChanged;
private T m_value;
public static implicit operator T(ListenableValue<T> value) => value.m_value;
public T value
{
get
{
return m_value;
}
set
{
m_value = value;
onChanged(m_value);
}
}
}
Now I want to support this:
ListenableValue<int> myValue = new ListenableValue<int>;
myValue += 3;
// Now myValue.m_value == 3
And this does not compile :
public static ListenableValue<T> operator +(ListenableValue<T> lhs, T rhs)
{
ListenableValue<T> copy = new ListenableValue<T>();
copy.onChanged = lhs.onChanged;
copy.m_value = lhs.m_value + rhs;
return copy;
}
I am also concerned about these things :
- Performance-wise, is
copy.onChanged = lhs.onChanged;costly? - The returned object is a new object with the same event handler reference. The two objects are now linked. It would be better to deep copy the listeners. But the best would be to disallow completly
+.