I am trying to implement observable native data types in C# (float, int, string, List). I should add that I am fairly new to C# and come from a C++ background.
My first thought was to have an observable interface like so:
public interface IObservable {
void registerObserver(IObserver observer);
void deregisterObserver(IObserver observer);
void notifyObservers();
}
And then to create a wrapper for a native data type (for example float) that overloads the operators so it is (mostly) seamless to use:
Float f1 = new Float(0);
Float f2 = f1 + 2;
This would have to be an abstract base class since interfaces can't overload operators.
Then I wanted to create an ObservableFloat which combined both ideas but called notifyObservers on any change to its state. The class using it would see it as a Float and would have no idea it was internally also an Observable.
For this I would normally overload the assignment operator so instead of doing something like:
return new Float(f1.value + f2.value);
It would modify the first instance and return it. But since assignment seems to always change the reference, I would loose my observable and its list of observers on the first assignment operation, right?
I found this post that implements an observer using events in C#: link This code:
private State _state;
public State MyState
{
get { return _state; }
set
{
if (_state != value)
{
_state = value;
Notify();
}
}
}
Does essentially what I want: when the State variable gets assigned a new value it does the assignment and also calls a function. Is there any way you can think of to achieve this while shielding the using class (Product in the example) from knowing that the variable is an Observable?