user2906831
user2906831

Reputation: 13

c# implicit operator

I'm writting an application that runs user defined algorithms. I want to keep track of variables used, so I created class TVar that will raise events when they are altered or peeked. I already did

public static implicit operator int(TVar v)
{
    Tracker.Track(v.name, EventType.Variable, EventAction.Peek, v.var);
    return (int)v.var;
}

Now I want to know when user changes value, and i Had

public static implicit operator TVar(int i)
{
    Tracker.Track(/* I need TVar.Name here */, EventType.Variable, EventAction.Change, i);
    return new TVar(i);
}

But as you may have noticed I use "name" to identify different TVars. Now, I create new TVar var1 and name it "first var", do some stuff with it (Tracker recieves information) and when i change var1 to some other int it looses it's name(because i returned new TVar, not the actual one) Help please!

Upvotes: 1

Views: 360

Answers (1)

Boris B.
Boris B.

Reputation: 5024

That won't work the way you want it to, because when you define an implicit conversion operator you cannot access the l-value from within the operator body. An assignment, by definition, always discards the value that the variable was referencing (if any).

TVar foo = new TVar("Foo", 13);
foo = 42;

After the first line foo is initialized, and it references an instance of TVar. But the second line discards foo's old value and replaces it with another TVar instance.

The only way to achieve what you want is to make an instance (non-static) method TVar.Assign(int).

public void Assign(int value)
{
    this.Value = value;
    Tracker.Track(this.Name, ...);
}

Upvotes: 3

Related Questions